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

如何用JQ将含Bash变量的JSON对象添加到JSON文件根层级?

问题背景

现有sample.json内容如下:

{"api": "3.0.0",
"data": {
"description": "something",
"title": "hello",
"version": "1.0",
"app": {
"name": "abc",
"id": "xyz"
}
}
}

需要在该文件根层级添加如下JSON对象(其中$username是Bash变量):

{"heading": {
"user": ["$username"]
}
}

当前使用的实现代码:

blob=$(jq -n --arg foo API_NAME '{"heading": {"user": [env.username]}}')
jq --argjson obj "$(echo $blob)" '. + $obj' < sample.json

想知道有没有更优的实现方案。

更优实现方案

你当前的写法多了不必要的中间步骤,完全可以一步完成,直接用jq的参数传递功能简化:

jq --arg username "$username" '. + {heading: {user: [$username]}}' sample.json

方案细节说明

  • 用--arg直接把Bash里的$username变量传入jq,比依赖env.username更可靠——如果username变量没导出,env.username会读取失败,而--arg不受这个限制
  • 直接在jq表达式里构造要添加的对象,省去了生成中间JSON字符串再传递的环节,代码更简洁,执行效率也更高
  • 如果需要直接修改原文件(不是只输出到终端),可以加上-i参数做原地编辑:
    jq -i --arg username "$username" '. + {heading: {user: [$username]}}' sample.json
    

另外,你原来代码里的--arg foo API_NAME是多余的,这个参数根本没用到,完全可以删掉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:55:22