How can I duplicate an existing object within a JSON array using jq?

痞子三分冷 提交于 2021-02-20 19:16:55

问题


I have the following geojson file:

{
    "type": "FeatureCollection",
    "features": [{
            "type": "Feature",
            "properties": {
                "LINE": "RED",
                "STATION": "Harvard"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [-71.118906072378209, 42.37402923068516]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "LINE": "RED",
                "STATION": "Ashmont"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [-71.063430144389983, 42.283883546225319]
            }
        }
    ]
}

I would like to append the second object within the "features" array to the end of it, creating 3 total objects. Using the below snippet errors out with "array ([{"type":"F...) and object ({"type":"Fe...) cannot be added". Is there a way to do this using jq without hardcoding the key:value pairs as seen here?

cat red_line_nodes.json | jq '.features |= . + .[length-1]' > red_line_nodes_2.json

回答1:


Short jq solution:

jq '.features |= . + [.[-1]]' red_line_nodes.json

The output:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "LINE": "RED",
        "STATION": "Harvard"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -71.11890607237821,
          42.37402923068516
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "LINE": "RED",
        "STATION": "Ashmont"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -71.06343014438998,
          42.28388354622532
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "LINE": "RED",
        "STATION": "Ashmont"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -71.06343014438998,
          42.28388354622532
        ]
      }
    }
  ]
}



回答2:


For reference, an alternative to using |= . + ... is to use +=. In your case, however, you would have to write:

.features += [.features[-1]]

so it's no shorter.



来源:https://stackoverflow.com/questions/48983196/how-can-i-duplicate-an-existing-object-within-a-json-array-using-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!