jq - Parse JSON file

by
Jeremy Canfield |
Updated: November 25 2024
| jq articles
Let's say you have the following in a file named my.json.
{
"data": {
"greeting": [
{
"foo": "hello"
},
{
"foo": "world"
}
]
}
}
Here is how you can parse my.json using jq on a Linux system.
~]$ cat my.json | jq
{
"data": {
"greeting": [
{
"foo": "hello"
},
{
"foo": "world"
}
]
}
}
To parse the "data" key.
~]$ cat my.json | jq .data
{
"greeting": [
{
"foo": "hello"
},
{
"foo": "world"
}
]
}
To parse the data and then greeting key.
~]$ cat my.json | jq .data.greeting
[
{
"foo": "hello"
},
{
"foo": "world"
}
]
Or like this, since the greeting key contains a list.
~]$ cat my.json | jq ".data.greeting[]"
[
{
"foo": "hello"
},
{
"foo": "world"
}
]
Let's say you have the following 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