繁体   English   中英

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

[英]Conditionally add json array using jq and bash

我正在尝试将一个只有一个数组元素的 json 数组添加到 json 中。 并且只有在它不存在时才必须添加它。 示例 json 如下。

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

上面是json,其中"schemes": ["https"],存在。 仅当使用以下代码不存在时才尝试添加方案。

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

当 json 数组元素“schemes”不存在时,我在文件中收到以下错误。 它返回一个空值和错误。 知道哪里出错了吗?

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

编辑:问题不在于如何将 bash 变量传递给 jq。

只需使用显式if条件来检查 JSON 结构的根级别中的属性schemes

schem='["https"]'

在 shell 中设置上述变量后,运行以下过滤器

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

紧跟在--argjson字段之后的参数是需要在jq的上下文中使用的参数,但是您试图在不正确的上下文中使用$schem

你甚至可以去一个水平进一步检查,即使schemes存在,如果它包含您所期望的价值,然后进行改写。 '..'的过滤器修改为

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

可以作为

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