You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:40:35