Bash:
Working with JSON
How to:
Bash itself lacks built-in JSON parsing capabilities, but jq
is a powerful command-line JSON processor that fills this gap. Here’s how to use it:
Reading a JSON file:
Sample data.json
:
{
"name": "Jane Doe",
"email": "[email protected]",
"location": {
"city": "New York",
"country": "USA"
}
}
To read and extract the name from the JSON file:
jq '.name' data.json
Output:
"Jane Doe"
Modifying JSON data:
To update the city to “Los Angeles” and write back to the file:
jq '.location.city = "Los Angeles"' data.json > temp.json && mv temp.json data.json
Parsing JSON from a variable:
If you have JSON in a Bash variable, jq
can still process it:
json_string='{"name": "John Doe", "email": "[email protected]"}'
echo $json_string | jq '.name'
Output:
"John Doe"
Working with arrays:
Given an array of items in JSON:
{
"items": ["apple", "banana", "cherry"]
}
To extract the second item (indexing starts at 0):
jq '.items[1]' data.json
Output:
"banana"
For more complex operations and filtering, jq
has a comprehensive manual and tutorials available online, making it a versatile tool for all your Bash/JSON needs.