简体   繁体   中英

Loop through JSON array shell script

I am trying to write a shell script that loops through a JSON file and does some logic based on every object's properties. The script was initially written for Windows but it does not work properly on a MacOS.

The initial code is as follows

    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

When ran on a MacOs, the whole file is processed at once, so it does not loop through objects. The closest I got to making it work - after trying a lot of suggestions - is as follows:

jq -r '.[]' "$file" | while read i; do

    for config in $i ; do

    currentKey=$(echo "$config" | jq -r '.Key')
    echo "$currentKey"

    done

done

The console result is parse error: Invalid numeric literal at line 1, column 6

I just cannot find a proper way of grabbing the JSON object and reading its properties.

JSON file example

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

Thank you in advance!

Try putting the $jsonStrings in doublequotes: done <<< "$jsonStrings"

Otherwise the standard shell splitting applies on the variable expansion and you probably want to retain the line structure of the output of jq .

You could also use this in bash :

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

That would save some resources. I am not sure about making this work on MacOS, though, so test this first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM