如果与给定键对应的值以指定的字符串开头,则使用jq更新JSON文档中的对象 [英] Using jq to update objects within a JSON document if the value corresponding to a given key starts with a specified string
本文介绍了如果与给定键对应的值以指定的字符串开头,则使用jq更新JSON文档中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有给定的JSON,并且想要更改所有元素的id
值,该值以name
元素中的test
开头:
I have the given JSON and want to change the id
value of all elements, which starts with test
in the name
element:
{
"other-value": "some-id",
"values": [
{
"name": "test-2017-12-01",
"id": "1"
},
{
"name": "othert",
"id": "2"
}
]
}
以下jq命令有效 jqplay
jq (.values[] | select(.name == "test-afs").id) |= "NEWID"
但是当我用startswith
尝试它停止工作时,我缺少什么? jqplay
But when I try it with startswith
it stops working, what am I missing? jqplay
(.values[] | select(.name | startswith("test")).id) |= "NEWID"
jq:错误(在14处):试图访问{"name":"test-afs","id":"id"}的元素"id"附近的路径表达式无效 退出状态5
jq: error (at :14): Invalid path expression near attempt to access element "id" of {"name":"test-afs","id":"id"} exit status 5
推荐答案
您也可以使用map
,如下所示:
You can also use map
, like this:
jq '(.values)|=(map((if .name|startswith("test") then .id="NEWID" else . end)))' file
输出:
{
"other-value": "some-id",
"values": [
{
"name": "test-2017-12-01",
"id": "NEWID"
},
{
"name": "othert",
"id": "2"
}
]
}
这篇关于如果与给定键对应的值以指定的字符串开头,则使用jq更新JSON文档中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文