【问题标题】:How can I duplicate an existing object within a JSON array using jq?如何使用 jq 在 JSON 数组中复制现有对象?
【发布时间】:2018-08-05 14:18:27
【问题描述】:

我有以下 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 个对象。使用以下 sn-p 错误,“无法添加数组 ([{"type":"F...) 和对象 ({"type":"Fe...)”。有没有办法使用 jq 来做到这一点,而不用硬编码 key:value 对,如 here 所见?

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

【问题讨论】:

  • 你到底想添加什么到数组中?
  • 我想复制现有对象之一并将其添加到数组中。我在 SO 上找到的先前答案仅显示了如何通过键入各种键和值来添加新对象;我想知道的是是否可以使用对现有文件的引用来添加新对象。
  • @m.brocks:删除了符合您上述评论的重复标签

标签: bash jq


【解决方案1】:

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

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

所以它不会更短。

【讨论】:

  • 但是它怎么会起作用呢?在|= 中,运算符左侧的“上下文”是数组,因此您必须使用. 来处理运算符右侧的数组,而在这里您必须在+= 运算符的两侧使用.features .对此有何解释?
  • @MartinMucha - (FOO += BAR) 具有 . as $in | (FOO += ($in|BAR)) 的语义
  • 谢谢!并不是说我真的明白这一点(这仍然让我发笑,当我学习 jq 时,我希望越来越少感到惊讶,而不是其他)。让我试着解释一下。 1.我将当前上下文保存到变量中。 2. 因为|+ 是IIRC |= . +) 我将通过向其添加由BAR 过滤的当前上下文来更新从当前上下文可访问的FOO。啊,是的,太好了,这正是你在这里所做的,它解释了不同之处。好的,我想我现在明白了。再次感谢。 (把这段文字放在这里,它有助于我理解它的写作,它可能同样适用于阅读)
【解决方案2】:

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

【讨论】:

  • 谢谢 - 正是我想要弄清楚的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
相关资源
最近更新 更多