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

如何用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命令解决方案。

解决方案

错误原因有两个:

  1. .arrays[]会遍历数组内所有元素,其中包含字符串类型的元素("a_string"、"another_string"),这类元素无法用.name索引,导致报错;
  2. 目标字段是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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:13:25