如何用jq修改混合字符串与对象的JSON数组中指定对象的properties?
问题描述
我有如下JSON文件:
{"header": "headername","arrays": ["a_string",{"name": "foo","properties": [{"type": "some_type1","url": "https://example.com","checksum": "d6fd580fe890b826250aa5d5a88bcdb28839cff4d447ba51536cda4ceae89c4e"}]},"another_string",{"name": "bar","properties": [{"type": "some_type2","url": "https://example.org","checksum": "d6fd580fe890b826250aa5d5a88bcdb28839cff4d447ba51536cda4ceae89c4e"}]}]}
希望修改其中name为"foo"的对象的properties块,预期输出如下:
{"header": "headername","arrays": ["a_string",{"name": "foo","properties": [{"type": "foo","url": "bar"}]},"another_string",{"name": "bar","properties": [{"type": "some_type2","url": "https://example.org"}]}]}
尝试使用命令:
.arrays[]| select(.name == "foo").sources |= [{"type" : "foo", "url" : "bar"}]
出现错误:
jq: error (at <stdin>:26): Cannot index string with string "name"
使用命令:
.| select(.name == "foo").sources |= [{"type" : "foo", "url" : "bar"}]
虽能解析但无任何修改效果,需要正确的jq命令解决方案。
解决方案
错误原因有两个:
.arrays[]会遍历数组内所有元素,其中包含字符串类型的元素("a_string"、"another_string"),这类元素无法用.name索引,导致报错;- 目标字段是
properties而非你写的sources。
正确的jq命令需要先过滤数组中**类型为对象且name等于"foo"**的元素,再修改其properties字段:
.arrays |= map(if type == "object" and .name == "foo" then .properties = [{"type": "foo", "url": "bar"}] else . end)
如果还需要移除bar对象里的checksum字段,可以补充处理逻辑:
.arrays |= map( if type == "object" then if .name == "foo" then .properties = [{"type": "foo", "url": "bar"}] elif .name == "bar" then .properties[0] |= del(.checksum) else . end else . end )
内容的提问来源于stack exchange,提问作者user22990699
相关产品推荐
相关产品推荐

