~/Blog

Brandon Rozek

Photo of Brandon Rozek

Computer Science PhD Candidate @ RPI, Writer of Tidbits, and Linux Enthusiast

Process JSON in the terminal with jq

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

The jq command is great for quickly viewing and manipulating JSON data. By default, the output is formatted is a human-readable way, and they provide an easy way to “filter” or access elements within the JSON data.

For example

echo "{\"firstName\": \"Brandon\", \"lastName\": \"Rozek\"}"  | jq

Outputs

{
  "firstName": "Brandon",
  "lastName": "Rozek"
}

To see what’s in the field firstName

echo "{\"firstName\": \"Brandon\", \"lastName\": \"Rozek\"}"  | jq .firstName

Other than quickly viewing JSON objects in the terminal. I have two other use cases for it.

1: Sanitizing Strings

echo $OUTPUT | jq -Rsa .
Flag Description
-R Don´t parse the input as JSON. Instead, each line of text is passed to the filter as a string.
-s Pass the entire input to the filter as a single long string
-a Produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.

2: Stringifying JSON

jq ".|tojson"

From the man pages

The tojson and fromjson builtins dump values as JSON texts or parse JSON texts into values, respectively.


Have any questions or want to chat: Reply via Email

Enjoyed this post?

Give me a high five (it's free): (0)

Published a response to this? :