如何使用JQ解析JSON字符串并合并至原数组父对象?
解析JSON字符串字段并合并回原数组的解决方案
问题场景
有如下JSON数组,其中activities字段是JSON格式的字符串:
[ { "id": 101, "created_at": "1987-10-12 03:20:22.903", "updated_at": "1987-10-12 01:20:36.019", "activities": "{\"hero\": \"batman\", \"weapon\": \"sword\", \"ts\": null, \"remote\": \"1\",\"game\": \"joker\", \"image\": \"bold\"}" }, { "id": 102, "created_at": "2022-10-12 11:20:22.903724", "updated_at": "2022-10-12 11:20:36.019043", "activities": "{\"hero\": \"superman\", \"weapon\": \"cape\", \"ts\": null, \"remote\": \"2\",\"game\": \"batman\", \"image\": \"kind\"}" } ]
可以用jq '.[].activities | fromjson?' test.json解析出activities的内容,但无法将解析后的字段合并回原对象并保留其他字段,期望得到的结果是将解析后的键值对合并到原对象,同时移除activities字段。
解决命令
使用以下jq命令即可实现需求:
jq 'map(. + (.activities | fromjson?) | del(.activities))' test.json
命令解释
map(...):遍历数组中的每一个对象. + (.activities | fromjson?):将当前对象与解析后的activities对象进行合并del(.activities):删除原对象中的activities字段
执行结果
执行命令后会输出如下内容:
[ { "id": 101, "created_at": "1987-10-12 03:20:22.903", "updated_at": "1987-10-12 01:20:36.019", "hero": "batman", "weapon": "sword", "ts": null, "remote": "1", "game": "joker", "image": "bold" }, { "id": 102, "created_at": "2022-10-12 11:20:22.903724", "updated_at": "2022-10-12 11:20:36.019043", "hero": "superman", "weapon": "cape", "ts": null, "remote": "2", "game": "batman", "image": "kind" } ]
内容的提问来源于stack exchange,提问作者cbetsworth_echo
相关产品推荐
相关产品推荐

