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

如何用Shell脚本在JSON文件指定数组索引后追加内容?

如何用Shell脚本向JSON指定位置插入内容?

需求是使用Shell脚本向JSON文件的指定位置插入新内容,输出符合要求的JSON格式。

现有test.json内容

{"reference": "Json Test","title": {"a": "Json Test"},"components": [{"reference": "Json Test","type": "panel","content": [{"link": "abc/123","label": {"a": "for test 123 - a","b": "for test 123 - b"}},{"link": "abc/456","label": {"a": "for test 456 - a","b": "for test 456 - b"}},{"link": "abc/789","label": {"a": "for test 789 - a","b": "for test 789 - b"}}]}]}

期望输出的JSON内容

{"reference": "Json Test","title": {"a": "Json Test"},"components": [{"reference": "Json Test","type": "panel","content": [{"link": "abc/123","label": {"a": "for test 123 - a","b": "for test 123 - b"}},{"link": "abc/101112","label": {"a": "for test 101112 - a","b": "for test 101112 - b"}},{"link": "abc/456","label": {"a": "for test 456 - a","b": "for test 456 - b"}},{"link": "abc/789","label": {"a": "for test 789 - a","b": "for test 789 - b"}}]}]}

之前尝试的问题命令

你之前的命令会替换掉原有索引位置的元素,而非插入:

jq '.components[].content[1] + { "link" : "test" } ' test.json

解决方案

方法1:使用jq的insert函数(推荐,jq 1.6+支持)

该方法直接在指定索引位置插入新元素,原有元素自动后移:

jq '.components[].content |= insert(1; {"link": "abc/101112", "label": {"a": "for test 101112 - a", "b": "for test 101112 - b"}})' test.json
  • |= 用于对components[].content数组进行更新赋值
  • insert(1; new_item) 表示在数组的索引1位置插入指定的新元素

方法2:数组切片拼接(兼容旧版jq)

如果你的jq版本不支持insert,可以通过数组切片拼接实现插入:

jq '.components[].content |= .[0:1] + [{"link": "abc/101112", "label": {"a": "for test 101112 - a", "b": "for test 101112 - b"}}] + .[1:]' test.json
  • .[0:1] 取原数组的前1个元素(索引0)
  • 中间拼接新元素组成的数组
  • .[1:] 取原数组从索引1开始的所有剩余元素
  • 三者拼接后得到插入新元素的数组

直接修改原文件

如果需要直接修改原test.json文件,添加-i参数(in-place编辑):

jq -i '.components[].content |= insert(1; {"link": "abc/101112", "label": {"a": "for test 101112 - a", "b": "for test 101112 - b"}})' test.json

内容的提问来源于stack exchange,提问作者Yaya Tseng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:25:29