Formatting JSON Data Using JQ in Shell Scripting

In this note, we will explore how to format JSON data using JQ.

Formatting JSON Data

JQ provides several functions for formatting JSON data. These functions can be used to pretty-print JSON data, compact JSON data, and to create new JSON objects from existing JSON data.

1. Pretty-Printing JSON Data

Pretty-printing JSON data is the process of adding indentation and line breaks to JSON data to make it more human-readable. JQ provides the . operator to pretty-print JSON data. Consider the following JSON data:

{
  "name": "John",
  "age": 25,
  "address": {
    "city": "New York",
    "state": "NY"
  }
}

To pretty-print this JSON data, we can use the following command:

jq '.' data.json

This will output the following JSON data:

{
  "name": "John",
  "age": 25,
  "address": {
    "city": "New York",
    "state": "NY"
  }
}

2. Compacting JSON Data

Compacting JSON data is the process of removing all unnecessary whitespace and line breaks from JSON data to make it more compact. JQ provides the -c option to compact JSON data. Consider the following JSON data:

{
  "name": "John",
  "age": 25,
  "address": {
    "city": "New York",
    "state": "NY"
  }
}

To compact this JSON data, we can use the following command:

jq -c '.' data.json

This will output the following JSON data:

{"name":"John","age":25,"address":{"city":"New York","state":"NY"}}

3. Creating New JSON Objects

JQ provides several functions for creating new JSON objects from existing JSON data. For example, we can use the map function to create a new JSON object that contains only the keys we want. Consider the following JSON data:

{
  "name": "John",
  "age": 25,
  "address": {
    "city": "New York",
    "state": "NY"
  }
}

To create a new JSON object that only contains the name and age keys, we can use the following command:

jq '{name, age}' data.json

This will output the following JSON data:

{
  "name": "John",
  "age": 25
}

We can also use the map function to transform the values of keys in a JSON object. For example, consider the following JSON data:

{
  "name": "John",
  "age": 25,
  "address": {
    "city": "New York",
    "state": "NY"
  }
}

To transform the name key to uppercase, we can use the following command:

jq '{name: .name | ascii_upcase, age}' data.json

This will output the following JSON data:

{
  "name": "JOHN",
  "age": 25
}

Also, see the example code shell-scripting-examples in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author