我想使用jq将数组元素添加到现有的json文件中。
element.json
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
original.json
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
我尝试关注
jq ".store.book += [input] " original.json element.json
以上工作正常,它添加了数组并显示如下所示的输出
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
现在有两个问题
首先,我尝试将更新的输出保存在以下的original.json中,但它清空了我的两个文件
jq ".store.book += [input] " original.json element.json > original.json
然后我用过,但未安装海绵,因此无法在生产中安装
jq ".store.book += [input] " original.json element.json | sponge original.json
以下内容适用于First
jq ".store.book += [input] " original.json element.json > original.tmp && mv original.tmp original.json
EDIT1: 根据反馈,我尝试了以下操作,但第二次仍然出错
jq ".store.book += [input.price=2] " original.json element.json
它引发错误
jq: error (at element.json:6): Invalid path expression near attempt to access element "price" of {"category":"fiction","aut...
答案 0 :(得分:1)
第一
[ input|.price |= $newprice ]
第二
最简单的方法是将输出写入一个临时文件,然后在检查是否成功之后将其移到适当位置。