【问题标题】:Add a new field containing a list of values to an existing JSON using jq使用 jq 将包含值列表的新字段添加到现有 JSON
【发布时间】:2019-04-10 15:23:48
【问题描述】:

我想将具有值 scan1scan2 的变量 IntendedFor 添加到现有 JSON 文件中。

我想用jq函数来做这个,我试过了:

cat existing.json | jq '.IntendedFor |= "["scan1", "scan2"]"' > output.json

但我收到错误消息并且 JSON 文件为空。

这就是我希望 output.json 文件的样子:

{  "existingjsonstuff": "andsoon",  
   "IntendedFor": ["scan1", "scan2"] 
}

我怎么得到这个??

【问题讨论】:

标签: json unix jq


【解决方案1】:

您可以使用+= [..] 运算符将所需元素添加到数组中。

jq '.IntendedFor += [ "scan1", "scan2" ]' existing.json > output.json

【讨论】:

    【解决方案2】:

    好的,谢谢!最终这段代码奏效了:

    cat existing.json | jq --argjson args '["scan1","scan2"]' '.{"IntededFor"] += $args' > output.json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多