【问题标题】:Conditionally add json array using jq and bash使用 jq 和 bash 有条件地添加 json 数组
【发布时间】:2020-01-28 10:14:51
【问题描述】:

我正在尝试将只有一个数组元素的 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。

【问题讨论】:

    标签: json bash jq


    【解决方案1】:

    只需使用显式 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多