英文:
jq : update json content when path is variable
问题
I have the following dataset in a file:
{
"storageSummary": 6.8624392E13,
"audit1": {
"auditScore": 1,
"suspensionScore": 1,
"onlineScore": 0.99743587,
"satelliteName": "us2.storj.io:7777"
},
"audit2": {
"auditScore": 1,
"suspensionScore": 1,
"onlineScore": 0.9992917,
"satelliteName": "saltlake.tardigrade.io:7777"
},
"audit3": {
"auditScore": 1,
"suspensionScore": 1,
"onlineScore": 0.99930555,
"satelliteName": "ap1.storj.io:7777"
}
}
I want to update the content (I'm storing the JSON into a variable, since I make several updates, then I'll create a new file), but the path of the data to update is variable:
For example, I have:
DS_SRC_FILE="test.json";
DS_OBJECT=$(jq -c '' ${DS_SRC_FILE})
ds="audit1"
new_name="toto"
jq --arg ds ${ds} --arg name ${new_name} '.[]|select(.value==$ds)|=(.satellitename = $name)' <<< ${DS_OBJECT}
So, of course, this is failing with parse error: Invalid numeric literal at line 2, column 36
.
What's the right way to do that, please?
英文:
I have the following dataset in a file :
{
"storageSummary": 6.8624392E13,
"audit1": {
"auditScore": 1,
"suspensionScore": 1,
"onlineScore": 0.99743587,
"satelliteName": "us2.storj.io:7777"
},
"audit2": {
"auditScore": 1,
"suspensionScore": 1,
"onlineScore": 0.9992917,
"satelliteName": "saltlake.tardigrade.io:7777"
},
"audit3": {
"auditScore": 1,
"suspensionScore": 1,
"onlineScore": 0.99930555,
"satelliteName": "ap1.storj.io:7777"
}
}
I want to update the content (I'm storing the json into a variable, since I make several updates, then I'll create a new file), but the path of the data to update is variable :
For example, I have :
DS_SRC_FILE="test.json"
DS_OBJECT=$(jq -c '' ${DS_SRC_FILE})
ds="audit1"
new_name="toto"
jq --arg ds ${ds} --arg name ${new_name} '.[]|select(.value==$ds)|=(.satellitename = $name)' <<< ${DS_OBJECT}
So, of course, this is failing with parse error: Invalid numeric literal at line 2, column 36
What's the right way to do that please ?
答案1
得分: 2
JSON不使用单引号,应该使用双引号,或者保持数字不带引号。
该命令仍然会失败:以.[]
开头会丢弃对象的键并返回值,所以你无法再访问"audit1"了。
另外,要改变数值,你可以使用普通的=
(而不需要select
),因为右边的表达式不受上下文影响:
jq --arg ds "$ds" --arg name "$new_name" '.[$ds]["satelliteName"] = $name' <<< "$DS_OBJECT"
还请注意,我给shell变量加了双引号,这样即使它们包含空格,命令也能正常工作。
英文:
JSON doesn't use single quotes. Use double quotes instead, or leave the number unquoted.
The command will still fail: starting with .[]
will throw away the keys of the object and return the values, so you don't have access to the "audit1" anymore.
Also, to change the value, you can use the plain =
(and without select
) as the right hand side is not sensitive to context:
jq --arg ds "$ds" --arg name "$new_name" '.[$ds]["satelliteName"] = $name' <<< "$DS_OBJECT"
Also note that I double quoted the shell variables which should make the command work even if they contained whitespace.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论