简体   繁体   English

使用 jq 和 bash 有条件地添加 json 数组

[英]Conditionally add json array using jq and bash

Am trying to add a json array with just one array element to a json.我正在尝试将一个只有一个数组元素的 json 数组添加到 json 中。 And it has to be added only if it does not already exist.并且只有在它不存在时才必须添加它。 Example json is below.示例 json 如下。

{
    "lorem": "2.0",
    "ipsum": {
        "key1": "value1",
        "key2": "value2"
    },
    "schemes": ["https"],
    "dorum" : "value3" 
}

Above is the json, where "schemes": ["https"], exists.上面是json,其中"schemes": ["https"],存在。 Am trying to add schemes only if it does not exist using the below code.仅当使用以下代码不存在时才尝试添加方案。

scheme=$( cat rendertest.json | jq -r '. "schemes" ')
echo $scheme
schem='["https"]'
echo "Scheme is"
echo $schem
if [ -z $scheme ]
then
echo "all good"
else 
jq --argjson argval  "$schem"  '. += { "schemes" : $schem }' rendertest.json > test.json
fi

I get the below error in a file when the json array element 'schemes' does not exist.当 json 数组元素“schemes”不存在时,我在文件中收到以下错误。 It returns a null and errors out.它返回一个空值和错误。 Any idea where am going wrong?知道哪里出错了吗?

null
Scheme is
["https"]
jq: error: schem/0 is not defined at <top-level>, line 1:
. += { "schemes" : $schem }                   
jq: 1 compile error

Edit: the question is not about how to pass on bash variables to jq.编辑:问题不在于如何将 bash 变量传递给 jq。

Just use an explicit if condition that checks for the attribute schemes in the root level of the JSON structure只需使用显式if条件来检查 JSON 结构的根级别中的属性schemes

schem='["https"]'

After setting the above variable in your shell, run the following filter在 shell 中设置上述变量后,运行以下过滤器

jq --argjson argval "$schem" 'if has("schemes")|not then .+= { schemes: $argval } else . end' json

The argument immediately after the --argjson field is the one that needs to be used in the context of jq , but you were trying to use $schem in the context which is incorrect.紧跟在--argjson字段之后的参数是需要在jq的上下文中使用的参数,但是您试图在不正确的上下文中使用$schem

You can even go one level further and check even if schemes is present and if it does not contain the value you expect, then make the overwrite.你甚至可以去一个水平进一步检查,即使schemes存在,如果它包含您所期望的价值,然后进行改写。 Modify the filter within '..' to'..'的过滤器修改为

( has("schemes")|not ) or .schemes != $argval )

which can be run as可以作为

jq --argjson argval "$schem" 'if ( (has("schemes")|not) or .schemes != $argval) then (.schemes: $argval) else . end'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM