将新数组添加到现有 JSON 文件 jq bash
Adding a new array to already existing JSON file jq bash
假设我有以下大 json
{
"firsttag": {
"secondtag": [
{
"thirdtag": [
{
"someothertag": [
{
"sample":"else"
},
{
"targetBlank": true,
}
],
"interestingtag": [
{
"refId": "A",
"target": "abc",
},
{
"refId": "B",
"target": "bbb",
},
{
"refId": "C",
"target": "ccc",
}
],
},
},
"overwrite": true
}
我的 JSON 可能在语法上不完美,但那是因为我已经编辑掉了一些东西。现在我想做的是,我想在 interestingtag
下添加另一个与其他输入类似的输入。例如,我希望它像
"interestingtag": [
{
"refId": "A",
"target": "abc"
},
{
"refId": "B",
"target": "bbb"
},
{
"refId": "C",
"target": "ccc"
},
{
"refId": "D",
"target": "ddd"
}
],
但我不知道该怎么做。我可以使用
检索正确的位置
jq '.firsttag.secondtag[0].thirdtag[0].interestingtag' myfile.json
但是当我尝试简单的
jq '.firsttag.secondtag[0].thirdtag[0].interestingtag + {"refId": "D", "refID": "C"}' myfile.json
我得到一个
jq: error: array and object cannot be added
知道我该怎么做吗?或者我做错了什么?
感谢您的帮助。
+
不向数组追加元素。您想使用 |= .+ [...]
合并数组,如 this answer
中所述
jq '.firsttag.secondtag[0].thirdtag[0].interestingtag |= .+ [{"refId": "D", "refID": "C"}]' myfile.json
假设我有以下大 json
{
"firsttag": {
"secondtag": [
{
"thirdtag": [
{
"someothertag": [
{
"sample":"else"
},
{
"targetBlank": true,
}
],
"interestingtag": [
{
"refId": "A",
"target": "abc",
},
{
"refId": "B",
"target": "bbb",
},
{
"refId": "C",
"target": "ccc",
}
],
},
},
"overwrite": true
}
我的 JSON 可能在语法上不完美,但那是因为我已经编辑掉了一些东西。现在我想做的是,我想在 interestingtag
下添加另一个与其他输入类似的输入。例如,我希望它像
"interestingtag": [
{
"refId": "A",
"target": "abc"
},
{
"refId": "B",
"target": "bbb"
},
{
"refId": "C",
"target": "ccc"
},
{
"refId": "D",
"target": "ddd"
}
],
但我不知道该怎么做。我可以使用
检索正确的位置jq '.firsttag.secondtag[0].thirdtag[0].interestingtag' myfile.json
但是当我尝试简单的
jq '.firsttag.secondtag[0].thirdtag[0].interestingtag + {"refId": "D", "refID": "C"}' myfile.json
我得到一个
jq: error: array and object cannot be added
知道我该怎么做吗?或者我做错了什么?
感谢您的帮助。
+
不向数组追加元素。您想使用 |= .+ [...]
合并数组,如 this answer
jq '.firsttag.secondtag[0].thirdtag[0].interestingtag |= .+ [{"refId": "D", "refID": "C"}]' myfile.json