gpt4 book ai didi

json - 如何使用 jq 更新 json 文档中的单个整数?

转载 作者:行者123 更新时间:2023-12-01 01:41:06 25 4
gpt4 key购买 nike

使用 jq我想更新一个 integer在来自环境变量的 JSON 文件中,但该属性被解析为字符串。

例如我想更新 task_definition.json 中的内存属性.该属性必须是整数,否则 API 会引发错误。

原始文件

{
"containerDefinitions": [
{
"cpu": 128,
"image": "...",
"memory": 512
...
}
]
}

jq 命令

export TASK_DEFINITION_MEMORY=256
jq '.containerDefinitions[0].memory = env.TASK_DEFINITION_MEMORY' task_definition.json > tmp.$$.json && mv tmp.$$.json task_definition.json

预期产出
{
"containerDefinitions": [
{
"cpu": 128,
"image": "...",
"memory": 256
...
}
]
}

实际产出
{
"containerDefinitions": [
{
"cpu": 128,
"image": "...",
"memory": "256"
...
}
]
}

最佳答案

尝试使用算术更新赋值运算符 //= https://stedolan.github.io/jq/manual/#Assignment

Arithmetic update-assignment: +=, -=, *=, /=, %=, //= jq has a few operators of the form a op= b, which are all equivalent to a |= . op b. So, += 1 can be used to increment values, being the same as |= . + 1.


export TASK_DEFINITION_MEMORY=256
jq '.containerDefinitions[0].memory //= env.TASK_DEFINITION_MEMORY' task_definition.json > tmp.$$.json && mv tmp.$$.json task_definition.json

关于json - 如何使用 jq 更新 json 文档中的单个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com