首页 > 解决方案 > 循环遍历 JSON 数组 shell 脚本

问题描述

我正在尝试编写一个循环遍历 JSON 文件并根据每个对象的属性执行一些逻辑的 shell 脚本。该脚本最初是为 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
    }
]

先感谢您!

标签: jsonmacosshell

解决方案


尝试把$jsonStrings双引号:done <<< "$jsonStrings"

否则,标准外壳拆分适用于变量扩展,您可能希望保留jq.

你也可以在bash

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

这样可以节省一些资源。不过,我不确定能否在 MacOS 上进行这项工作,因此请先进行测试。


推荐阅读