jq examples
References
- jq: a lightweight and flexible command-line JSON processor.
- jq manual
- My https://github.com/jqlang/jq/issues/2246 recap:
- Q: Is there a jq –slurp builtin .ie the inverse of .[] ?
- A: No
Input
{
"ts": 20250624,
"title": "Some random data",
"people": [
{ "name": "Alfred", "age": 34, "country": "Canada" },
{ "name": "Bob", "age": 40, "country": "USA" },
{ "name": "Charles", "age": 22 }
],
"countries": {
"Canada": { "population": 40, "capital": "Ottawa" },
"USA": { "population": 340, "capital": "Washington, D.C." },
"Germany": { "population": 83 },
"India": { "population": 1438, "capital": "New Delhi" }
}
}
Example 1: create string out of document data
jq -r '. | "export TS=\"\(.ts)\"\nexport TITLE=\"\(.title)\"\nexport PEOPLE=\"\(.people|length)\"\nexport COUNTRIES=\"\(.countries|length)\""'
export TS="20250624"
export TITLE="Some random data"
export PEOPLE="3"
export COUNTRIES="4"
Example 2: keys
jq 'keys'
jq keys
["countries", "people", "title", "ts"]
jq 'keys[]'
jq 'keys | .[]'
"countries"
"people"
"title"
"ts"
jq -r 'keys[]'
jq -r 'keys | .[]'
countries
people
title
ts
Example 3: get some fields from dictionary
jq '. | {ts,title}'
jq '{ts,title}'
{
"ts": 20250624,
"title": "Some random data"
}
Example 4: get some fields from array of dictionaries
jq '.people | [.[] | {name,age}]'
[
{ "name": "Alfred", "age": 34 },
{ "name": "Bob", "age": 40 },
{ "name": "Charles", "age": 22 }
]
Example 5: compose array of strings from array of dictionaries
jq '.people | [.[] | {name,age} | join("|")]'
["Alfred|34", "Bob|40", "Charles|22"]
Example 6: to_entries
jq '.countries | to_entries'
[
{
"key": "Canada",
"value": { "population": 40, "capital": "Ottawa" }
},
{
"key": "USA",
"value": { "population": 340, "capital": "Washington, D.C." }
},
{
"key": "Germany",
"value": { "population": 83 }
},
{
"key": "India",
"value": { "population": 1438, "capital": "New Delhi" }
}
]
Example 7: convert array to dictionary → from_entries
jq '.people | [.[] | {"key":.name,"value":.}] | from_entries'
{
"Alfred": { "name": "Alfred", "age": 34, "country": "Canada" },
"Bob": { "name": "Bob", "age": 40, "country": "USA" },
"Charles": { "name": "Charles", "age": 22 }
}
Example 8: dictionary filter → to_entries + select() + from_entries
jq '.countries | to_entries | [.[] | select(.value.population > 100)] | from_entries'
{
"USA": {
"population": 340,
"capital": "Washington, D.C."
},
"India": {
"population": 1438,
"capital": "New Delhi"
}
}