Work with JSON in Bash

Working with JSON data in Bash typically involves parsing and manipulating JSON strings using command-line tools like jq or built-in capabilities like awk and grep. Here’s an example of how you can work with JSON in Bash using the jq tool:

  1. Parsing JSON: jq is a powerful command-line JSON processor that allows you to extract and filter data from JSON strings. Assuming you have a JSON file named data.json with the following content:
  "name": "John Doe",
  "age": 30,
  "email": "",
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "country": "USA"

You can extract specific values using jq. For example, to retrieve the value of the “name” field:

name=$(jq -r '.name' data.json)
echo "Name: $name"

This will output: Name: John Doe.

2. Modifying JSON: jq can also be used to modify JSON data. For example, if you want to update the “age” field to 35:

jq '.age = 35' data.json > updated.json

This will output a JSON object containing only the specified fields.

3. Iterating over JSON arrays: If your JSON data contains arrays, you can iterate over them using a loop. Assuming you have a JSON array like this:

  { "name": "John" },
  { "name": "Jane" },
  { "name": "Mark" }

You can iterate over the array and extract values:

# Iterate over the array and extract names
jq -r '.[].name' data.json |
while read -r name; do
    echo "Name: $name"

This will output each name in the array.

These examples demonstrate some basic operations using jq for working with JSON data in Bash. jq provides extensive functionality for more advanced JSON processing, including filtering, mapping, grouping, and more. You can refer to the jq documentation for further details on its capabilities and usage.

Leave a Comment

Your email address will not be published. Required fields are marked *