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

求助:使用jq命令替换JSON文件中Stock字段的指定值

使用jq替换JSON中特定Stock字段的值

嗨,别担心,刚接触jq确实会有点懵,我一步步给你讲怎么实现这个需求~

首先,核心的jq命令逻辑是:选中Stock字段,判断它的值是不是"Add to cart"或者"add",如果是就替换成"In stock",不是的话保持原内容不变。

针对单个JSON对象的情况

如果你的JSON文件是单个对象(比如下面这样):

{
"Product": "T-Shirt",
"Stock": "Add to cart"
}

用这条命令就行:

jq '.Stock |= if . == "Add to cart" or . == "add" then "In stock" else . end' input.json

针对包含多个对象的JSON数组

如果你的JSON是数组格式(比如多个产品的集合):

[
{"Product": "Hat", "Stock": "add"},
{"Product": "Shoes", "Stock": "Out of stock"}
]

只需要加个map()来遍历数组里的每个对象:

jq 'map(.Stock |= if . == "Add to cart" or . == "add" then "In stock" else . end)' input.json

怎么修改原文件?

jq默认只会把结果输出到终端,不会直接修改原文件。如果想覆盖原文件:

  • 在Linux/macOS上,可以用sponge工具(需要先安装moreutils包):
    jq 'map(.Stock |= if . == "Add to cart" or . == "add" then "In stock" else . end)' input.json | sponge input.json
    
  • 在Windows PowerShell里,可以这样写:
    (jq '.Stock |= if . == "Add to cart" or . == "add" then "In stock" else . end' input.json) | Set-Content input.json
    
  • 最稳妥的方式是先输出到新文件,确认没问题再替换原文件:
    jq '...' input.json > output.json
    # 检查output.json没问题后,替换原文件
    mv output.json input.json
    

举个实际的例子,假设你的input.json内容是:

[
{"Product": "Shirt", "Stock": "Add to cart"},
{"Product": "Mug", "Stock": "add"},
{"Product": "Bag", "Stock": "Out of stock"}
]

运行命令后,输出的结果会变成:

[
{"Product": "Shirt", "Stock": "In stock"},
{"Product": "Mug", "Stock": "In stock"},
{"Product": "Bag", "Stock": "Out of stock"}
]

这样就完美实现你要的效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:57:32