【发布时间】: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。
【问题讨论】: