3751

Is there a (Unix) shell script to format JSON in human-readable form?

Basically, I want it to transform the following:

{ "foo": "lorem", "bar": "ipsum" } 

... into something like this:

{ "foo": "lorem", "bar": "ipsum" } 
13
  • stackoverflow.com/a/12892039/998291 Commented Oct 15, 2012 at 8:51
  • 10
    I rolled my own a short while back: github.com/exhuma/braindump/tree/master/jsonformat The code is very simple, using python's own json library, but I added pygments as well to get syntax highlighting. Commented Nov 9, 2012 at 13:40
  • Stumbled on to this but then found Json Pretty and I quite like it. Typekit uses it in their API examples, so there's some klout behind it ^^ Commented Nov 21, 2012 at 14:42
  • 13
    Be warned: python -m json.tool does not always produce valid JSON. (Hint: 1e1000) Commented Sep 11, 2015 at 16:48
  • 1
    Too many (identical) answers, it is hard to find a listing of possible solutions. I've made a benchmark to try and summarise those. I hope this won't be yet another useless answer! Commented Apr 9, 2020 at 11:08

63 Answers 63

1 2
3
0

Found 4 already available tools in my Gentoo system:

From package dev-libs/json-glib 19K ELF

json-glib-format -p file.json 

From package dev-lang/perl 4,9K Perl script

(keeps unicode symbols as-is)

cat file.json | json_pp 

From package dev-libs/yajl 43K ELF

cat file.json | json_reformat 

From package dev-lang/python

(escapes unicode symbols to unreadable \u hex notation, had to replace python with python3 on debian system)

python -m json.tool file.json 
Sign up to request clarification or add additional context in comments.

Comments

-2

You can also use online tools instead if that is an option for you.

I find http://jsonprettyprint.net to be the simplest and easiest.

Comments

-4

I know that the original post asked for a shell script, but there are so many useful and irrelevant answers that probably did not help the original author. Adding on to irrelevance :)

BTW I could not get any command line tools to work.

If somebody want simple JSON JavaScript code, they could do:

JSON.stringfy(JSON.parse(str), null, 4) 

http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos

Here is JavaScript code that not only pretties the JSON, but orders them by their attribute or by attribute and level.

If input is

{ "c": 1, "a": {"b1": 2, "a1":1 }, "b": 1}, 

it either prints (groups all the objects together):

{ "b": 1, "c": 1, "a": { "a1": 1, "b1": 2 } } 

OR (just orders by key):

{ "a": { "a1": 1, "b1": 2 }, "b": 1, "c": 1 } 

Comments

1 2
3