如果我忽略了一些非常明显的东西,那就是我的意思; 我刚刚发现jq并尝试使用它来更新一个JSON值而不影响周围的数据.
我想将curl结果传递给jq,更新一个值,并将更新的JSON传递给一个curl -X PUT.就像是
curl http://example.com/shipping.json | jq '.' field: value | curl -X PUT http://example.com/shipping.json
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经一起使用了它sed,但是在查看了一些|=运算符示例后,jq我确信我不需要这些.
这是一个JSON示例 - 我将如何jq设置"local": false,同时保留其余的JSON?
{
"shipping": {
"local": true,
"us": true,
"us_rate": {
"amount": "0.00",
"currency": "USD",
"symbol": "$"
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*ado 106
您可以使用=运算符设置对象的值. |=另一方面用于更新值.这是一个微妙但重要的区别.过滤器的上下文发生变化.
由于您要将属性设置为常量值,请使用=运算符.
.shipping.local = false
Run Code Online (Sandbox Code Playgroud)
请注意,在为属性设置值时,它不一定必须存在.您可以通过这种方式轻松添加新值.
.shipping.local = false | .shipping.canada = false | .shipping.mexico = true
Run Code Online (Sandbox Code Playgroud)
Pau*_*nes 45
更新一个值(将 .foo.bar 设置为“新值”):
jq '.foo.bar = "new value"' file.json
Run Code Online (Sandbox Code Playgroud)
使用变量更新值(将 .foo.bar 设置为“hello”):
variable="hello"; jq --arg variable "$variable" '.foo.bar = $variable' file.json
Run Code Online (Sandbox Code Playgroud)
小智 10
与操作符 |= 类似的功能是 map。map 将适用于避免对数组的先前过滤器的要求......
想象你的数据是一个数组(这个例子很常见)
[
{
"shipping": {
"local": true,
"us": true,
"us_rate": {
"amount": "1.00",
"currency": "USD",
"symbol": "$"
}
}
},
{
"shipping": {
"local": true,
"us": true,
"us_rate": {
"amount": "1.00",
"currency": "USD",
"symbol": "$"
}
}
}
]
Run Code Online (Sandbox Code Playgroud)
因此有必要将代码中的数组视为:
http://example.com/shipping.json | jq '.[] | .shipping.local = "new place"' | curl -X PUT http://example.com/shipping.json
Run Code Online (Sandbox Code Playgroud)
或者使用精心设计的用于在每个数组元素中工作的 map 函数作为
http://example.com/shipping.json | jq 'map(.shipping.local = "new place")' | curl -X PUT http://example.com/shipping.json
Run Code Online (Sandbox Code Playgroud)
观察
为了那些正在学习的人,你在 jq 的用法上也犯了一些错误,只是考虑它确实“读取”了第一个参数作为程序,因此所有需要的命令都应包含在调用后的第一个字符串中程序。
| 归档时间: |
|
| 查看次数: |
43885 次 |
| 最近记录: |