Bootstrap FreeKB - jq - Loop JSON
jq - Loop JSON

Updated:   |  jq articles

Let's say you have the following JSON in a file named my.json.

{
  "employees": [
    {
      "name": "John Doe",
      "department": "IT"
    },
    {
      "name": "Jane Doe",
      "department": "Sales"
    },
    {
      "name": "Jack Doe",
      "department": "HR"
    }
  ]
}

 

Here is how you can loop through the employees list.

jq -c '.employees[]' my.json | while read item; do echo $item; done

 

Or like this.

while read item; do echo $item; done < <(jq -c '.employees[]' my.json)

 

Which should return something like this.

{"name": "John Doe", "department": "IT"}
{"name": "Jane Doe", "department": "Sales"}
{"name": "Jack Doe", "department": "HR"}

 

Let's say you have a JSON file with multiple lists.

{
  "fruits": [
    {
      "color": "red",
      "value": "apple"
    },
    {
      "color": "yellow",
      "value": "banana"
    },
    {
      "color": "green",
      "value": "grapes"
    }
  ],
  "veggies": [
    {
      "color": "white",
      "value": "onion"
    },
    {
      "color": "orange",
      "value": "carrot"
    },
    {
      "color": "green",
      "value": "pepper"
    }
  ]
}

 

Here is how you can loop through the tops lists (fruits and veggies) 

jq '' my.json | while read item; do echo $item; done

 

Which should return the following.

{
"fruits": [{"color": "red","value": "apple"},{"color": "yellow","value": "banana"},{"color": "green","value": "grapes"}],
"veggies": [{"color": "white","value": "onion"},{"color": "orange","value": "carrot"},{"color": "green","value": "pepper"}]
}

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 67e4bd in the box below so that we can be sure you are a human.