简体   繁体   English

使用 jq 将包含值列表的新字段添加到现有 JSON

[英]Add a new field containing a list of values to an existing JSON using jq

I would like to add a variable IntendedFor with values scan1 and scan2 to an existing JSON file.我想将一个值为scan1scan2的变量IntendedFor添加到现有的 JSON 文件中。

I would like to do this with jq function, I tried:我想用jq函数来做到这一点,我试过:

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

but I get the error and and empty JSON file.但我收到错误和空的 JSON 文件。

This is what i want the output.json file to look like:这就是我希望 output.json 文件的样子:

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

How do i get this??我怎么得到这个??

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

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

Yes, thank you!是的,谢谢! Eventually this code worked:最终这段代码起作用了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM