遍历JSON数组外壳脚本

时间:2019-11-20 16:34:08

标签: json macos shell

我正在尝试编写一个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
    }
]

提前谢谢!

1 个答案:

答案 0 :(得分:1)

尝试将dbSendQuery放在双引号中:$jsonStrings

否则,标准的shell拆分将应用于变量扩展,您可能希望保留done <<< "$jsonStrings"输出的行结构。

您也可以在jq中使用它:

bash

这样可以节省一些资源。不过,我不确定要在MacOS上实现此功能,因此请先进行测试。