Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

gq is like jq but for GeoJSON.

Design Goals

  • Same syntax as jq
  • GeoJSON spec compliant
  • Support vector operations like:
    • buffer
    • intersection
    • union
    • difference
  • Very good error messages
  • Easy to use
  • Performs well with large GeoJSON files

Introduction

gq uses jq 1.8 as its reference implementation.

For all supported features, gq should work like jq, plus extra operations on geometries.

gq aims to support a minimal subset of most-used core jq functionality, just enough to be useful in service of its main function of manipulating GeoJSON.

Supported jq Features

See jq 1.8 manual

jq FeatureExample
Identity.
Object Identifier-Index.foo, .foo.bar
Object Index.["foo"]
Array Index.[2]
Array/String Slice.[2:4]
Pipe.a | .b | .c
Parenthesis(. + 2) * 5
JSON data types1, "a", true, null, [], {}, etc.
Array construction[1, 2, 3]
Object construction{"a": 42, "b": 17}
Addition+/add
Subtraction-
Multiplication, division, modulo*, /, %
Conditional operators==, !=
Comparison operators>, >=, <, <=
Boolean operatorsand, or, not
Sorting arrayssort
Lengthlength
Mapmap
Plain assignment1=
Update assignment1|=
Arithmetic update assignment1+=, -=, *=, /=, %=
Variable Binding.realnames as $names

Unsupported Features

These features are out of scope for this tool with no plans for implementation:

  • iterators
  • generators
  • user-defined functions
  • scoping
  • streaming
  • modules

Notable Differences from jq

gq does not support outputting streams of non-JSON data via iterators (.[]) and generators (,). Rather, since gq is very JSON and GeoJSON focused, every transformation produces valid JSON.

This means, for example, that there is no select since that function will produce no output if the condition does not match, and “no output” is not valid JSON.

map and filter

It is of course still possible to manipulate collections of data. Instead of:

[.[] | . + 1]

You would use map (this is also valid jq):

map(. + 1)

And instead of:

map(select(. >= 2))

You would use filter:

filter(. >= 2)

  1. Only object and array lookups are supported for path expressions (left-hand side). ↩ ↩2 ↩3

Features

First Class FeatureCollections

Any function that operates on an array can also take a FeatureCollection where each item is a Feature.

Automatic Array from Multiple Input Files

In jq, there is an optional command line argument --slurp/-s which puts the entire input stream into an array and runs the program against that.

In gq, this happens automatically if there are multiple input files.

Any number of files containing JSON or GeoJSON can be passed in and they will appended in order to an array that can then be operated on.

As an example, this command:

gq '.' feature.json geometry.json

will return an array containing a Feature and a Geometry.

If only one file is passed in, no array will be created.

File Arguments

Input files are automatically available as variables with a specific naming scheme.

File arguments have a dollar sign ($) prefix followed by the argument index:

  • $0 references the array, assuming multiple input files
  • $1 references the first file
  • $2 references the second file
  • $3 references the third file, etc.

If only one file is passed in, the original value is available as $0.

As an example, if you want to union together all Features in a FeatureCollection and merge all of their properties, you could do:

gq 'union | feature | .properties = ($0.features | map(.properties) | add)' feature_collection.json

Try in the gq Playground

Tutorial

gq programs can be thought of as a series of transformations on JSON with special support for GeoJSON.

Types

All JSON types are supported: numbers, strings, booleans, arrays, objects, and null. You construct and nest them in a familiar way:

[{"a": 1}, true, false, null, 2.5, "hello"]

It is important to note that in gq both the input and output must be valid JSON (this is different from jq which only requires that the input be JSON). Moreover, the data must always be valid JSON at every step in the process of executing a gq program.

Identity

The simplest gq program is just a dot: .. This is the identity function which simply passes the input along and does nothing with it.

For example:

echo '[1, 2, 3]' | gq '.'

returns

[
  1,
  2,
  3
]

Try in the gq Playground

Notice that, like in jq, the JSON output is pretty-printed by default.

Property and Index Lookups

You can look up object properties via .<property_name>:

echo '{"a": 1}' | gq '.a'

returns

1

Array index lookups work similarly (zero-based):

echo '[1, 2, 3]' | gq '.[1]'

returns

2

These lookups can be chained together:

echo '{"a": {"b": {"c": [1, 2, 3]}}}' | gq '.a.b.c[0]'

returns

1

Try in the gq Playground

This nested lookup can also be expressed as:

.a | .b | .c | .[0]

If a non-existent key or index is requested:

echo '{"a": 1}' | gq '.z'

null is returned.

Pipe

The | operator chains sub-expressions together.

In this example, we look up the value of property a and pass that value off to another expression that adds 1 to it:

echo '{"a": 1}' | gq '.a | . + 1'

returns

2

The .a expression looks up the value of the property “a” and returns it.

The | passes that return value into the next expression. In the context of that expression, the value of . is that return value of 1. We then add 1 to 1 and get 2.

If we go ahead and compare that result to 2:

echo '{"a": 1}' | gq '.a | . + 1 == 2'

returns

true

Try in the gq Playground

As you can see, typical arithmetic (+, -, *, /, %) and comparison (==, !=, >, <, >=, <=) operators are supported in ways that should hopefully be familiar.

Assignment

The = operator assigns values and works with lookups:

echo '{"a": 1}' | gq '.a = 2'

returns

{
  "a": 2
}

It also works with nested lookups:

echo '{"a": {"b": 1}}' | gq '.a.b = 2'

returns

{
  "a": {
    "b": 2
  }
}

Note that if the key does not exist, it will be created automatically, including any intermediate structures, with null filled in for any missing values.

For example:

echo '{"a": 1}' | gq '.a.b[1].c = 2'

returns

{
  "a": {
    "b": [
      null,
      {
        "c": 2
      }
    ]
  }
}

Try in the gq Playground

There is also the update assignment operator (|=), which is subtly different and may be more appropriate depending on your use case (see this section of the jq manual), as well as arithmetic update operators (+=, -=, *=, /=, %=).

Looping and filtering

There are no loops in gq, but the built-in functions map and filter should meet a similar need.

As with other programming languages, map applies a function to every item in a collection:

echo '[1, 2, 3]' | gq 'map(. * 2)'

returns

[
  2,
  4,
  6
]

Try in the gq Playground

And filter keeps only items in a collection for which the applied function returns true:

echo '[1, 2, 3]' | gq 'filter(. > 1)'

returns

[
  2,
  3
]

Try in the gq Playground

Aggregation

There is deliberately no reduce function in the interest of simplicity.

Hopefully, built-in functions (eg. add, length) will meet your needs in cases where you might otherwise want to use reduce. If not, please see Issues.

Accessing original input data

We’ve looked at . as a way to reference the current state of the program. There are also special variables automatically available that reference the original value passed into the program.

The variable $0 references the original input:

echo '[1, 2, 3]' | gq 'add | {"original": $0, "sum": .}'

returns

{
  "original": [
    1,
    2,
    3
  ],
  "sum": 6
}

Try in the gq Playground

Working with GeoJSON

gq’s main purpose is to manipulate GeoJSON, and all functionality is ultimately in service of this goal.

Let’s look at a practical example given a FeatureCollection like so, saved locally as feature_collection.json:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [0, 0],
            [2, 0],
            [2, 2],
            [0, 2],
            [0, 0]
          ]
        ]
      },
      "properties": null
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [1, 1],
            [3, 1],
            [3, 3],
            [1, 3],
            [1, 1]
          ]
        ]
      },
      "properties": null
    }
  ]
}

Union

We can merge the geometries of all of its Features via:

gq 'union' feature_collection.json

returning a new GeoJSON Geometry:

{
  "type": "Polygon",
  "coordinates": [
    [
      [0, 2],
      [0, 0],
      [2, 0],
      [2, 1],
      [3, 1],
      [3, 3],
      [1, 3],
      [1, 2],
      [0, 2]
    ]
  ]
}

Try in the gq Playground

Feature construction

We can then wrap that in a Feature via:

gq 'union | feature' feature_collection.json

returning:

{
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0, 2],
        [0, 0],
        [2, 0],
        [2, 1],
        [3, 1],
        [3, 3],
        [1, 3],
        [1, 2],
        [0, 2]
      ]
    ]
  },
  "properties": null
}

Try in the gq Playground

Bounding box

We can set the bounding box on the feature via:

gq 'union | feature | .bounding_box = (.geometry | bounding_box)' feature_collection.json

This sets the bounding_box property on the feature to output of feeding the Feature’s geometry into the bounding_box function.

The output then looks like this:

{
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0, 2],
        [0, 0],
        [2, 0],
        [2, 1],
        [3, 1],
        [3, 3],
        [1, 3],
        [1, 2],
        [0, 2]
      ]
    ]
  },
  "properties": null,
  "bounding_box": {
    "type": "Polygon",
    "coordinates": [
      [
        [3, 0],
        [3, 3],
        [0, 3],
        [0, 0],
        [3, 0]
      ]
    ]
  }
}

Try in the gq Playground

Validation

Finally, we can validate our output as valid GeoJSON via validate, which only returns an error if the GeoJSON is invalid and otherwise does nothing. In this case, the GeoJSON is indeed valid!

The complete gq command is:

gq 'union | feature | .bounding_box = (.geometry | bounding_box) | validate' feature_collection.json

Try in the gq Playground

Examples

For a gentler introduction and simpler examples, see the Tutorial.

Merge all counties within a 10 mile radius of Philadelphia

Given this FeatureCollection of counties in the Delaware Valley (del_val.geojson):

gq '
(
  find(.properties.fips == "42101").geometry |
  centroid |
  buffer(10, {unit: "miles"})
) as $philly_buffer |
    merge(.geometry | intersects($philly_buffer))
' del_val.geojson

This works by:

  1. Finding the Feature corresponding to Philadelphia county (FIPS county code of 42101)
  2. Calculating the centroid of its geometry
  3. Generating a buffer with a radius of 10 miles around the centroid
  4. Merging all Features whose geometries intersect with that buffer

Historical Markers in Philadelphia

Given this FeatureCollection of historical markers (historical_markers.geojson) and this FeatureCollection of the city limits of Philadelphia (City_Limits.geojson):

gq '
($2 | union) as $city_limits |
  $1 |
  filter(
    .geometry != null and (
      .geometry | contained_by($city_limits)
    )
  )
' historical_markers.geojson City_Limits.geojson

This works by:

  1. Unioning the geometries of all Features within the city limits FeatureCollection ($2 refers to the second input file)
  2. Filtering the historical markers FeatureCollection ($1 refers to the first input file) by non-null geometries falling within the city limits

GeoJSON

These functions operate on any GeoJSON (FeatureCollection, Feature, or Geometry).

intersection

Given any number of GeoJSONs, return the overlapping regions as a new Geometry.

Example

Given this array of Features:

[
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [0, 0],
          [2, 0],
          [2, 2],
          [0, 2],
          [0, 0]
        ]
      ]
    },
    "properties": null
  },
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [1, 1],
          [3, 1],
          [3, 3],
          [1, 3],
          [1, 1]
        ]
      ]
    },
    "properties": null
  }
]

intersection returns

{
  "type": "Polygon",
  "coordinates": [
    [
      [1, 2],
      [1, 1],
      [2, 1],
      [2, 2],
      [1, 2]
    ]
  ]
}

Try in the gq Playground

difference

Given any number of GeoJSONs, return the regions from the first GeoJSON which are not in any of the following GeoJSONs as a new Geometry.

Example

Given this FeatureCollection:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [0, 0],
            [2, 0],
            [2, 2],
            [0, 2],
            [0, 0]
          ]
        ]
      },
      "properties": null
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [1, 1],
            [3, 1],
            [3, 3],
            [1, 3],
            [1, 1]
          ]
        ]
      },
      "properties": null
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [1, 0],
            [2, 0],
            [2, 1],
            [1, 1],
            [1, 0]
          ]
        ]
      },
      "properties": null
    }
  ]
}

difference returns

{
  "type": "Polygon",
  "coordinates": [
      [
        [0, 2],
        [0, 0],
        [1, 0],
        [1, 2],
        [0, 2]
      ]
    ]
}

Try in the gq Playground

symmetric_difference

Like difference, but excludes overlapping regions (i.e. exclusive or).

Example

Given this FeatureCollection:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [0, 0],
            [2, 0],
            [2, 2],
            [0, 2],
            [0, 0]
          ]
        ]
      },
      "properties": null
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [1, 1],
            [3, 1],
            [3, 3],
            [1, 3],
            [1, 1]
          ]
        ]
      },
      "properties": null
    }
  ]
}

symmetric_difference returns

{
  "type": "MultiPolygon",
  "coordinates": [
    [
      [
        [0, 2],
        [0, 0],
        [2, 0],
        [2, 1],
        [1, 1],
        [1, 2],
        [0, 2]
      ]
    ],
    [
      [
        [1, 3],
        [1, 2],
        [2, 2],
        [2, 1],
        [3, 1],
        [3, 3],
        [1, 3]
      ]
    ]
  ]
}

Try in the gq Playground

union

Given any number of GeoJSONs, merge the regions of both into a new Geometry.

Example

Given this array of Features:

[
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [0, 0],
          [2, 0],
          [2, 2],
          [0, 2],
          [0, 0]
        ]
      ]
    },
    "properties": null
  },
  {
    "type": "Feature",
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        [
          [1, 1],
          [3, 1],
          [3, 3],
          [1, 3],
          [1, 1]
        ]
      ]
    },
    "properties": null
  }
]

union returns

{
  "type": "Polygon",
  "coordinates": [
      [
        [0, 2],
        [0, 0],
        [2, 0],
        [2, 1],
        [3, 1],
        [3, 3],
        [1, 3],
        [1, 2],
        [0, 2]
      ]
    ]
}

Try in the gq Playground

Geometry

These functions operate on a GeoJSON Geometry.

bounding_box

Find the bounding box of a GeoJSON geometry, returning a Polygon.

Example

Given:

{
  "type": "Polygon",
  "coordinates": [
    [
      [0, 1],
      [1, 0],
      [2, 2],
      [0, 1]
    ]
  ]
}

bounding_box returns

{
  "type": "Polygon",
  "coordinates": [
    [
      [2, 0],
      [2, 2],
      [0, 2],
      [0, 0],
      [2, 0]
    ]
  ]
}

Try in the gq Playground

buffer

Add a buffer around any Geometry (eg. buffer(1)) where the default unit is kilometers.

A second, optional parameter is supported which takes values like so:

{
    unit: "kilometers" | "meters" | "miles",
    line_join: "round" | "miter" | "bevel",
    line_cap: "butt" | "round" | "square"
}

The default values are:

{
    unit: "kilometers",
    line_join: "round",
    line_cap: "round"
}

As an example:

buffer(1000, {unit: "meters"})

is equivalent to:

buffer(1, {unit: "kilometers"})

or simply:

buffer(1)

centroid

Find the centroid of a GeoJSON geometry, returning a Point.

Example

Given:

{
  "type": "Polygon",
  "coordinates": [
    [
      [0, 0],
      [2, 0],
      [2, 2],
      [0, 2],
      [0, 0]
    ]
  ]
}

centroid returns

{
  "type": "Point",
  "coordinates": [1, 1]
}

Try in the gq Playground

concave_hull

Find the concave hull of a GeoJSON geometry (LineString, MultiLineString, MultiPoint, MultiPolygon, or Polygon), returning a Polygon.

Example

Given:

{
  "type": "MultiPoint",
  "coordinates": [
    [0.0, 0.0],
    [3.0, 0.0],
    [1.0, 2.0],
    [0.0, 4.0]
  ]
}

concave_hull returns

{
  "type": "Polygon",
  "coordinates": [
    [
      [3, 0],
      [1, 2],
      [0, 4],
      [0, 0],
      [3, 0]
    ]
  ]
}

Try in the gq Playground

contains

Whether the input geometry contains the argument value (returns a boolean).

Example

Given:

{
  "type": "Polygon",
  "coordinates": [
    [
      [2, 0],
      [2, 2],
      [0, 2],
      [0, 0],
      [2, 0]
    ]
  ]
}

the program

contains({"type": "Point", "coordinates": [1, 1]})

returns true.

Try in the gq Playground

contained_by

Like contains, except the arguments are reversed.

convex_hull

Find the convex hull of a GeoJSON geometry, returning a Polygon.

Example

Given:

{
  "type": "Polygon",
  "coordinates": [
    [
      [0.0, 0.0],
      [4.0, 0.0],
      [4.0, 1.0],
      [1.0, 1.0],
      [1.0, 4.0],
      [0.0, 4.0],
      [0.0, 0.0]
    ]
  ]
}

convex_hull returns

{
  "type": "Polygon",
  "coordinates": [
    [
      [4, 0],
      [4, 1],
      [1, 4],
      [0, 4],
      [0, 0],
      [4, 0]
    ]
  ]
}

Try in the gq Playground

feature

Wrap a geometry in a Feature.

Example

Given:

{
  "type": "Point",
  "coordinates": [0, 0]
}

feature returns

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [0, 0]
  },
  "properties": null
}

Try in the gq Playground

simplify

Simplify a geometry (Polygon, MultiPolygon, LineString, MultiLineString) given an epsilon value (eg. simplify(1.0)).

Collections

These functions operate on an array or FeatureCollection.

clip

Given a FeatureCollection (or an array of Features) and a mask geometry, return a new collection where the Feature geometries include only regions within the mask:

$feature_collection | clip($mask)

clip($mask) is equivalent to:

map(.geometry = ([.geometry, $mask] | intersection))

erase

Given a FeatureCollection (or an array of Features) and a mask, return a new collection where the Feature geometries include only regions outside of the mask.

$feature_collection | erase($mask)

erase($mask) is equivalent to:

map(.geometry = ([.geometry, $mask] | difference))

feature_collection

Wrap an array of Features in a FeatureCollection.

filter

Based on a predicate, filter down an array:

filter(. >= 2)

or a FeatureCollection:

filter(.properties.state == "PA")

returning the same collection type.

find

Like filter, but return only the first item in the array or Feature in the FeatureCollection.

This is equivalent to:

filter(<predicate>) | .[0]

map

Apply an expression to each item in an array:

map(. + 1)

or Feature in a FeatureCollection:

map(.geometry | buffer(5))

returning the same collection type.

merge

Like union, but with a predicate to use for filtering:

merge(.properties.COUNTY == "46")

This is equivalent to:

filter(<predicate>) | union

sort

Sort an array or a FeatureCollection based on the sort rules of jq.

Miscellaneous

assert

Make an assertion on the current state of the program, returning the original JSON value unmodified if the assertion passes.

Examples

echo "[1, 2, 3]" | gq 'assert(length == 3, "array length must be 3")'

returns

[1, 2, 3]

Try in the gq Playground

but

echo "[1, 2, 3]" | gq 'assert(length == 2, "array length must be 2")'

returns

gq: array length must be 2

Try in the gq Playground

compact

Remove all non-essential whitespace from the JSON output (as opposed to the default of pretty-printing the JSON).

Example

Given:

{
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0, 0],
        [2, 0],
        [2, 2],
        [0, 2],
        [0, 0]
      ]
    ]
  },
  "properties": {"a": 1}
}

compact returns

{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[0, 0],[2, 0],[2, 2],[0, 2],[0, 0]]]},"properties":{"a":1}}

Try in the gq Playground

validate

Validate as GeoJSON. Returns the original JSON value unmodified if valid.

Examples

Given valid GeoJSON:

{
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0, 0],
        [2, 0],
        [2, 2],
        [0, 2],
        [0, 0]
      ]
    ]
  },
  "properties": {"a": 1}
}

validate returns

{
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [0, 0],
        [2, 0],
        [2, 2],
        [0, 2],
        [0, 0]
      ]
    ]
  },
  "properties": {"a": 1}
}

Try in the gq Playground

but given invalid GeoJSON

{
  "a": 1
}

validate returns

gq: Invalid GeoJSON structure: missing field `type`

Try in the gq Playground

gq Playground

gq Playground
<h1>Playground</h1>
<p>
  <label for="json">JSON</label>
  <textarea id="json" placeholder="Enter JSON input here..."></textarea>
</p>
<p>
  <label for="program">gq</label>
  <textarea id="program" placeholder="Enter gq program here..."></textarea>
</p>
<button id="run">Run</button>

<pre id="output"></pre>

<script type="module" src="./app.js"></script>