Posts Json in command line
Post
Cancel

Json in command line

When I am debugging a part of a code which does not work, I print quite often some dictionary of a json object in my shell. Most of the time it happens in one line quite difficult to read, so I open bracket and format my JSON to have better readability.

Recently I discover jq, which can manage to print your JSON file in your terminal. I will save a lot of time.

1
2
3
4
5
echo '{"foo": 123, "bar": "abc"}' | jq
{
  "foo": 123,
  "bar": "abc"
}

I want to access an attribute of my JSON I only need to write

1
2
echo '{"foo": 123, "bar": "abc"}' | jq '.bar'
"abc"

You can also mix curl and jq if you want to display beautifully the result of an API in your terminal.

1
2
3
4
5
6
7
8
9
10
11
12
13
curl https://api.github.com/repos/dianedelallee/python-exercise |jq
{
  "id": 144120613,
  "node_id": "MDEwOlJlcG9zaXRvcnkxNDQxMjA2MTM=",
  "name": "python-exercise",
  "full_name": "dianedelallee/python-exercise",
  "private": false,
   ...
   ...
  "default_branch": "master",
  "network_count": 0,
  "subscribers_count": 1
}
This post is licensed under CC BY 4.0 by the author.