Plouf
Plouf

Reputation: 397

Filter objects in geojson based on a specific key

I try to edit a geojson file to keep only objects that have the key "name". The filter works but I can't find a way to keep the other objects and, specifically, the geometry and redirect the whole stuff to a new geojson file. Is there a way to display the whole object after filtering one of its children objects?

Here is an example of my data. The first object has the "name" property and the second hasn't:

{
  "features": [
    {
      "type": "Feature",
      "id": "way/24824633",
      "properties": {
        "@id": "way/24824633",
        "highway": "tertiary",
        "lit": "yes",
        "maxspeed": "50",
        "name": "Rue de Kleinbettingen",
        "surface": "asphalt"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            5.8997935,
            49.6467825
          ],
          [
            5.8972561,
            49.6467445
          ]
        ]
      }
    },
    {
      "type": "Feature",
      "id": "way/474396855",
      "properties": {
        "@id": "way/474396855",
        "highway": "path"
      },
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            5.8020608,
            49.6907648
          ],
          [
            5.8020695,
            49.6906054
          ]
        ]
      }
    }
  ]
}

Here is what I tried, using jq

cat file.geojson | jq '.features[].properties | select(has("name"))'

The "geometry" is also a child of "features" but I can't find a way to make the selection directly from the "features" level. Is there some way to do that? Or a better path to the solution?

So, the required ouput is:

{
  "type": "Feature",
  "id": "way/24824633",
  "properties": {
    "@id": "way/24824633",
    "highway": "tertiary",
    "lit": "yes",
    "maxspeed": "50",
    "name": "Rue de Kleinbettingen",
    "surface": "asphalt"
  },
  "geometry": {
    "type": "LineString",
    "coordinates": [
      [
        5.8997935,
        49.6467825
      ],
      [
        5.8972561,
        49.6467445
      ]
 ]}}

Upvotes: 1

Views: 679

Answers (1)

hek2mgl
hek2mgl

Reputation: 158150

You can assign the filtered list back to .features:

jq '.features |= map(select(.properties|has("name")))'

Upvotes: 3

Related Questions