循环执行JSON数组外壳脚本



我正在尝试编写一个shell脚本,该脚本在JSON文件中循环,并根据每个对象的属性执行一些逻辑。该脚本最初是为Windows编写的,但在MacOS上无法正常工作。

初始代码如下

documentsJson=""        
jsonStrings=$(cat "$file" | jq -c '.[]')
while IFS= read -r document; do
# Get the properties from the docment (json string)
currentKey=$(echo "$document" | jq -r '.Key')
encrypted=$(echo "$document" | jq -r '.IsEncrypted')
# If not encrypted then don't do anything with it
if [[ $encrypted != true  ]]; then
echoComment " Skipping '$currentKey' as it's not marked for encryption"
documentsJson+="$document,"
continue
fi
//some more code
done <<< $jsonStrings

当在MacO上运行时,整个文件会同时处理,因此不会在对象中循环。在尝试了很多建议后,我最接近实现它的方法如下:

jq -r '.[]' "$file" | while read i; do
for config in $i ; do
currentKey=$(echo "$config" | jq -r '.Key')
echo "$currentKey"
done
done

控制台结果为parse error: Invalid numeric literal at line 1, column 6

我只是找不到一种正确的方法来获取JSON对象并读取其属性。

JSON文件示例

[
{
"Key": "PdfMargins",
"Value": {
"Left":0,
"Right":0,
"Top":20,
"Bottom":15
}
},
{
"Key": "configUrl",
"Value": "someUrl",
"IsEncrypted": true
}
]

提前谢谢!

尝试将$jsonStrings放在双引号中:done <<< "$jsonStrings"

否则,标准的shell拆分将应用于变量展开,并且您可能希望保留jq输出的行结构。

你也可以在bash:中使用它

while IFS= read -r document; do
...
done < <(jq -c '.[]' < "$file")

这样可以节省一些资源。不过,我不确定是否能在MacOS上实现这一点,所以请先测试一下。