Gio O Gio O - 3 years ago 171
JSON Question

Moving a json nested key-value pair up one level with jq

I want to use jq to move a nested key:value pair up one level. So given a geojson array of objects like this:

{
"type" : "FeatureCollection",
"features" : [ {
"type" : "Feature",
"geometry" : {
"type" : "MultiLineString",
"coordinates" : [ [ [ -74, 40 ], [ -73, 40 ] ] ]
},
"properties" : {
"startTime" : "20160123T162547-0500",
"endTime" : "20160123T164227-0500",
"activities" : [ {
"activity" : "car",
"group" : "car"
} ]
}
} ]
}


I want to return the exact same object, but with
"group": "car"
in the
features
object. So the result would look something like this:

{
"type" : "FeatureCollection",
"features" : [ {
"type" : "Feature",
"geometry" : {
"type" : "MultiLineString",
"coordinates" : [ [ [ -74, 40 ], [ -73, 40 ] ] ]
},
"properties" : {
"type" : "move",
"startTime" : "20160123T162547-0500",
"endTime" : "20160123T164227-0500",
"group" : "car",
"activities" : [ {
"activity" : "car"
} ]
}
} ]
}


This seems simple, but somehow I'm struggling to figure out how to do it with jq. Help appreciated!

Answer Source

jq solution:

jq '(.features[0].properties.group = .features[0].properties.activities[0].group)
 | del(.features[0].properties.activities[0].group)' input.json

The output:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "MultiLineString",
        "coordinates": [
          [
            [
              -74,
              40
            ],
            [
              -73,
              40
            ]
          ]
        ]
      },
      "properties": {
        "startTime": "20160123T162547-0500",
        "endTime": "20160123T164227-0500",
        "activities": [
          {
            "activity": "car"
          }
        ],
        "group": "car"
      }
    }
  ]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download