0

I am trying to loop through the JSON having an array nested within. I am trying to achieve this with the help of Shell script and JQ. But I am getting weird output as there is space in one of the values.

Please help me with this:

Below is the snippet I am using:

==fruits.json==

{
    "fruits": [
        {
            "name" : "Orange",
            "colour": "Orange"

        },
        {
            "name" : "Red Grapes",
            "colour": "Red"

        }
    ]
}

==Shell script: fruits.sh==

#!/bin/bash

call_api() {
    FILE="/akasia/RestApiTestAutomation/fruits.json"
    jsonFile=$(jq . $FILE)
    #echo "This is array " $(echo $jsonFile | jq -c '.fruits[]' )
    for row in $(echo "${jsonFile}" | jq -c '.fruits[]' );
    do
        echo "The row is " $row
    done
}
call_api

I am seeing below output:

The row is  {"name":"Orange","colour":"Orange"}
The row is  {"name":"Red
The row is  Grapes","colour":"Red"}

The expected output is:

The row is  {"name":"Orange","colour":"Orange"}
The row is  {"name":"Red Grapes","colour":"Red"}

Please help me with this. Thanks in advance!

  • https://www.starkandwayne.com/blog/bash-for-loop-over-json-array-using-jq/ my first google hit on `jq iterate over array with bash`. Do __not__ use `for i in $(..)`, it's a common __anti__ -pattern. Read https://mywiki.wooledge.org/BashFAQ/001 – KamilCuk Feb 15 '21 at 09:03
  • 1
    Thanks @KamilCuk, That helped me a lot :) – Mahendra Sawarkar Feb 18 '21 at 11:02

0 Answers0