如何使用jq复制JSON数组中的现有对象?

时间:2018-02-26 07:13:38

标签: bash jq

我有以下geojson文件:

{
    "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]
            }
        }
    ]
}

我想在"功能"中附加第二个对象。数组到它的末尾,创建3个总对象。使用"数组([{" type":" F ...)和对象({" type":" Fe ...)无法添加"。有没有办法使用jq执行此操作而无需对密钥进行硬编码:值对here

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

2 个答案:

答案 0 :(得分:4)

jq 解决方案:

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

输出:

{
  "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
        ]
      }
    }
  ]
}

答案 1 :(得分:1)

供参考,使用|= . + ...的替代方法是使用+=。但是,在您的情况下,您必须写:

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

所以它不短。