By AnC


2008-12-09 08:20:45 8 Comments

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"
}

30 comments

@Uma sankar pradhan 2012-11-23 13:30:17

Install yajl-tools with the command below:

sudo apt-get install yajl-tools

then,

echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat

@Joseph Lust 2014-06-21 14:15:40

Awesome. Does not require another language/interpreter and is in the package repo's, no need to brew!

@Vita Pluvia 2013-03-05 18:34:05

You can use: jq

It's very simple to use and it works great! It can handle very large JSON structures, including streams. You can find their tutorials here.

Usage examples:

$ jq --color-output file1.json file1.json | less -R

$ command_with_json_output | jq .

$ jq # stdin/"interactive" mode, just enter some JSON

$ jq <<< '{ "foo": "lorem", "bar": "ipsum" }'
{
  "bar": "ipsum",
  "foo": "lorem"
}

Or use jq with identity filter:

$ jq '.foo' <<< '{ "foo": "lorem", "bar": "ipsum" }'
"lorem"

@Matthew Flaschen 2014-11-04 01:17:09

There is also a --sort-keys option, which is helpful in some cases.

@jimbo 2015-01-02 23:00:34

jq is a great tool, which I discovered through this answer. Be aware however that it requires whole objects to work on. It won't start outputting results until it has read in the whole input object.

@Hover Ruan 2015-04-21 07:44:09

Working with curl: curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5‌​' | jq '.'

@peak 2015-09-04 02:38:52

"jq ." is great as a pretty-printer, but it comes with a caveat: jq (up to and including jq version 1.5) will alter the values of very large and very small numbers because it parses numeric values as IEEE 754 64-bit values. To check whether your favorite pretty-printer has the same issue, try this value: 1e1000. Note that python -mjson.tool fails this test badly in that it produces Infinity, which is not even JSON.

@Chad 2016-11-18 05:33:03

As a note, you can redirect the formatted result to a file: echo '{ "foo": "lorem", "bar": "ipsum" }' | jq . > myfile.

@jchook 2016-12-28 20:10:36

@Meekohi the alternative is "unnecessary use of echo". Super happy to have found the <<< operator – exactly what I was looking for.

@ericsoco 2017-05-11 20:39:21

Here's a nice runthru of jq's features, including a section on pretty-printing: shapeshed.com/jq-json/#how-to-pretty-print-json. One way to write your ugly file to a pretty one: cat ugly.json | jq '.' | cat > pretty.json

@Luc 2017-08-16 07:44:15

Typing cat | jq . and then pasting used to work. No longer, it seems... jq just exits for some reason. Now I use my paste-from-clipboard alias: clipread | jq. The alias is alias clipread='xclip -out -selection clipboard' (add this to your ~/.bashrc or zshrc or whatever-rc, and choose an alias name that you like).

@Hendry 2017-10-13 10:59:47

Reading from a file jq . <<< cat filename.json

@phil294 2018-01-13 23:07:11

jq is the best because it prints in colors!

@shellter 2018-03-19 12:39:16

@Luc . Try cat - | jq . with pasted text. Good luck to all.

@codeforester 2018-11-09 23:56:08

jq -C to include colors. If you piping the output to less, then export LESS="-R" and then use jq -C ... | less. Without -C, jq suppresses colors when the output is not directed to a terminal, as in | command or > file.

@Lucian Wischik 2019-05-27 05:18:26

jq has the irritating property that it will silently loose precision on numbers. E.g. if your input has "foo": 16962331779841739123 then jq '.' will silently round the number to "foo": 16962331779841739000. If I'm only looking for a pretty-printer, then I'd chose one that's not lossy.

@TheAmigo 2020-07-24 20:42:58

+1 unlike the python solution, jq also handles some improperly formatted data (e.g. Ubiquiti's NVR backup files) like this: echo '{"foo":0}{"bar":1}' | jq where python chokes on the missing comma and gives no formatted output.

@Ulysse BN 2020-04-09 11:07:15

TL;DR: for performances, use jj -p < my.json.

Benchmark

I took some solutions here and benchmarked them with the next dummy script:

function bench {
    time (
      for i in {1..100}; do
        echo '{ "foo": "lorem", "bar": "ipsum" }'  | [email protected] > /dev/null
      done
    )
}

Here's the result on my mac (8 GB 2133 MHz LPDDR3, 2.3 GHz Intel Core i5):

bench python -m json.tool
# 3.60s user 1.24s system 88% cpu 5.448 total
bench jq
# 2.79s user 0.29s system 89% cpu 3.453 total
bench bat -p -l json
# 5.77s user 0.99s system 95% cpu 7.080 total
bench jj -p
# 0.19s user 0.26s system 85% cpu 0.529 total

Thanks @peak and your answer for this discovery of jj!

@Schmitzi 2019-09-30 13:11:46

You can simply use standard tools like jq or json_pp.

echo '{ "foo": "lorem", "bar": "ipsum" }' | json_pp

or

echo '{ "foo": "lorem", "bar": "ipsum" }' | jq

will both prettify output like the following (jq even more colorful):

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

The huge advantage of jq is that it can do A LOT more if you'd like to parse and process the json.

@David H 2020-04-28 18:42:49

json_pp was on my Mac - but not jq. Thanks!

@Schmitzi 2020-04-29 10:53:40

@DavidH - does this help: stackoverflow.com/questions/37668134/…

@Evgeny Karpov 2016-07-27 07:54:32

a simple bash script for pretty json printing

json_pretty.sh

#/bin/bash

grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'

Example:

cat file.json | json_pretty.sh

@Evgeny Karpov 2016-07-27 16:58:50

Thanks for the feedback. I just wrote this script today for personal using and it worked fine in my cases. I made fixes, now it's smaller and without this problem. There is not a goal to support completely format, but i can make other fixes if necessary.

@Zaboj Campula 2016-10-06 10:21:35

That is only working answer I found. I have an embedded linux - no rubby, no javascript, no access to internet to download python modules... I have slightly different awk that does not support %*c notation so I changed the printf to c=0; while (c++<offset) printf " "; printf $0;. And my awk has different regex escaping and backslash does not work in []. I changed the regexes to /^[[{]/ and /[]}]/.

@Blag 2018-02-20 14:12:53

This should be the accepted, as it's full native and don't require third party software...

@Evgeny Karpov 2018-02-21 03:31:18

@Blag the script looked broken after your editing, please explain or correct it. thanks!

@Blag 2018-02-21 06:47:52

@EvgenyKarpov nice catch, no need for a full rollback, just the grep that was erased by mistake ;)

@Rotsor 2019-06-23 15:45:20

This script is pretty fragile and it doesn't support full json syntax. For example it turns { "\"" : "quote" } into { "\" " : " } (on multiple lines).

@Matthis Kohli 2019-08-15 11:41:07

This works pretty well with piping. getMyLogs | grep -Eo ...

@Ahmed M 2019-08-19 09:40:57

Thanks dude, I wanted a quick way to format an 8MB one-liner json, in bare simple bash.

@pcko1 2020-03-09 15:36:43

In my case, I also needed to execute json_pretty.sh, e.g. cat file.json | ./json_pretty.sh

@harish2704 2018-09-25 06:44:51

A one-line solution using Node.js will look like this:

$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

For example:

$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

@Matthis Kohli 2020-03-09 14:55:22

no output for me with this example even though I voted this up long time ago. Something changed ...

@harish2704 2020-03-09 16:22:13

@MatthisKohli: I just rechecked this on Node V12.x and it is working. There is nothing magic in this code. fs.readFileSync(0) reads stdin of the current process and JSON.stringify formats the JSON. So, there is very less chance for breaking API change

@Grav 2018-09-03 07:15:26

bat is a cat clone with syntax highlighting:

Example:

echo '{"bignum":1e1000}' | bat -p -l json

-p will output without headers, and -l will explicitly specify the language.

It has colouring and formatting for JSON and does not have the problems noted in this comment: How can I pretty-print JSON in a shell script?

@Arpit Rathod 2018-07-16 12:09:08

You can use this simple command to achieve the result:

echo "{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }"|python -m json.tool

@Eugene C 2019-10-07 20:29:28

Best answer in my opinion. Small and easy to remember and doesn't require installing any non-standard tools.

@pushNpop 2019-10-10 02:50:12

python -m json.tool doesn't seem to preserve the order of the JSON object.

@Yada 2016-10-15 13:43:04

If you don't mind using a third-party tool, you can simply curl to jsonprettyprint.org. This is for the case where you can't install packages on the machine.

curl -XPOST https://jsonprettyprint.org/api -d '{"user" : 1}'

@Niel de Wet 2017-05-29 13:13:13

To pipe stdin to this command, do something like this: echo '{ "foo": "lorem", "bar": "ipsum" }' | curl -XPOST https://jsonprettyprint.org/api -d @-

@Orest Ivasiv 2014-08-12 21:12:51

Here is a Groovy one-liner:

echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'

@Pablo Fernandez heelhook 2013-08-06 10:14:25

Here is a Ruby solution that is better than Json's prettify command. The gem colorful_json is fairly good.

gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
  "foo": "lorem",
  "bar": "ipsum"
}

@Salman A 2012-04-27 10:37:19

JSONLint has an open-source implementation on GitHub that can be used on the command line or included in a Node.js project.

npm install jsonlint -g

and then

jsonlint -p myfile.json

or

curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less

@Adrien Joly 2020-06-18 12:50:10

I recommend not installing nodejs/npm dependencies globally => I'd use npx instead: curl -s "http://api.twitter.com/1/users/show/user.json" | npx jsonlint | less (i.e. no npm install necessary)

@nelaaro 2012-03-07 10:41:28

My JSON files were not parsed by any of these methods.

My problem was similar to the post Is Google data source JSON not valid?.

The answer to that post helped me find a solution.

It is considered to be invalid JSON without the string keys.

{id:'name',label:'Name',type:'string'}

must be:

{"id": "name", "label": "Name", "type": "string"}

This link gives a nice comprehensive comparison of some of the different JSON parsers: http://deron.meranda.us/python/comparing_json_modules/basic

Which led me to http://deron.meranda.us/python/demjson/. I think this one parser is much more fault tolerant than many others.

@Salman A 2012-04-27 10:50:31

JSON does not allow single quotes as delimiters and a sane JSON parser should reject such input.

@Peter Mortensen 2019-04-09 13:08:28

The last two links seem to be broken ("The server at deron.meranda.us is taking too long to respond").

@vadimk 2012-01-25 20:33:41

With JavaScript/Node.js: take a look at the vkBeautify.js plugin, which provides pretty printing for both JSON and XML text.

It's written in plain JavaScript, less than 1.5 KB (minified) and very fast.

@Somu 2010-07-12 13:00:30

I use the "space" argument of JSON.stringify to pretty-print JSON in JavaScript.

Examples:

// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);

// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');

From the Unix command-line with Node.js, specifying JSON on the command line:

$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
  '{"foo":"lorem","bar":"ipsum"}'

Returns:

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

From the Unix command-line with Node.js, specifying a filename that contains JSON, and using an indent of four spaces:

$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
      .readFileSync(process.argv[1])), null, 4));"  filename.json

Using a pipe:

echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
"\
 s=process.openStdin();\
 d=[];\
 s.on('data',function(c){\
   d.push(c);\
 });\
 s.on('end',function(){\
   console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
 });\
"

@Gurpartap Singh 2011-08-11 18:05:45

For debugging objects in Node.js, you should really use sys.inspect() instead of JSON.stringify(). Here's why: markhansen.co.nz/inspecting-with-json-stringify

@danorton 2012-09-02 14:30:18

Downvoted. The OP is about a "*nix command-line script" and this answer is a different context.

@calvinf 2012-09-17 20:08:38

@danorton: JS can be used from the commandline via node.js and other similar solutions.

@Timo Tijhof 2013-05-02 02:30:08

Use node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" on the Unix command-line (with nodejs)

@RusHughes 2013-06-25 14:00:39

node -e 'var f = require("./package.json"); console.log(f.name);' Even shorter :D :D :D

@Julian D. 2014-11-05 16:26:18

No need for the console: node -p "JSON.stringify(JSON.parse(process.argv[1]), null, '\t');" also outputs the result to STDOUT.

@kplshrm7 2015-09-19 12:50:42

JSON.stringify i always use

@Lukasz Wiktor 2016-02-17 13:39:02

It sucks that the script is different for a filename vs. stdin

@strugee 2018-04-08 06:41:57

@LukaszWiktor it doesn't have to be if your *nix supports /dev/stdin!

@Reino 2019-01-17 23:08:19

You can use Xidel.

Xidel is a command line tool to download and extract data from HTML/XML pages or JSON-APIs, using CSS, XPath 3.0, XQuery 3.0, JSONiq or pattern templates. It can also create new or transformed XML/HTML/JSON documents.

Xidel pretty-prints by default:

$ xidel -s - -e '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
  "foo": "lorem",
  "bar": "ipsum"
}

or:

$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -s - -e .
{
  "foo": "lorem",
  "bar": "ipsum"
}

@B Bycroft 2009-12-17 09:48:55

With Python 2.6+ you can just do:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

or, if the JSON is in a file, you can do:

python -m json.tool my_json.json

if the JSON is from an internet source such as an API, you can use

curl http://my_url/ | python -m json.tool

For convenience in all of these cases you can make an alias:

alias prettyjson='python -m json.tool'

For even more convenience with a bit more typing to get it ready:

prettyjson_s() {
    echo "$1" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool "$1"
}

prettyjson_w() {
    curl "$1" | python -m json.tool
}

for all the above cases. You can put this in .bashrc and it will be available every time in shell. Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'.

@YOUR ARGUMENT IS VALID 2011-04-19 16:33:02

With other versions of Python you can install simplejson and use python -msimplejson.tool

@Shrikant Sharat 2011-12-03 03:24:14

You could pipe that onto pygmentize -l javascript to get syntax colored output in your command line. Edit: If you have pygments installed that is.

@Everett Toews 2012-05-03 19:19:18

alias ppj='python -mjson.tool'; echo '{"foo": "lorem", "bar": "ipsum"}' | ppj

@Chris Nash 2012-06-26 20:35:46

A great answer, only caution I have with it is it does sort the keys on output - which you might need to be aware of.

@imwilsonxu 2012-10-15 06:59:28

In myy .vimrc "nnoremap <f5> :%!python -m json.tool<CR>:w<CR>"

@user1071136 2012-10-16 11:24:05

This seems to escape Unicode characters into \uXXXX, which might be a disadvantage.

@Andz 2012-11-19 03:56:32

This is tip is super handy when viewing Riak or (other JSON-capable servers) output! e.g. curl blah.com:8089 | python -mjson.tool You absolutely don't need to install or configiure anything except python, which is usually there already.

@Aswin Kumar 2013-03-03 20:29:28

hey can anyone help with adding this as a external command in gedit? Edit: got it; Tools -> Manage External Toosl -> new (+) -> add "python -mjson.tool " -> Select Input = Current Document, Output = Replace Current Document. Cheers!

@Mike Weller 2013-03-08 11:20:16

Anyone got the same for XML?

@svidgen 2013-04-18 18:54:01

@Jonathan Hartley 2013-07-11 09:12:27

and add syntax highlighting by piping the output into 'colout -t json'. Requires 'pip install colout' first.

@user7610 2014-02-03 15:20:23

@user1071136 To keep the Unicode characters in the output it is necessary to make your own script. import sys import json j = json.load(sys.stdin) json.dump(j, sys.stdout, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))

@J.N. 2014-02-24 07:12:48

It doesn't accept top level arrays, so not all json sadly.

@piotr.d 2015-02-06 16:42:45

@ShrikantSharat: since version 1.5 Pygments support json type as well.

@Clint Eastwood 2015-02-25 17:42:53

I've created an alias: alias pretty='python -mjson.tool | pygmentize -l json so that I can just run: command params | pretty. Hope this helps. PS: Should anyone manages to extend this to a) remove the curl-output I'm seeing every time and/or b) NOT sort the json keys; please do let me know, I will be highly thankful.

@nishanths 2015-05-03 04:08:52

And if the JSON is in a file: $ cat file.json | python -m json.tool

@peak 2015-09-04 02:44:15

Another problem with python -m json.tool as a JSON pretty-printer is that it does not always print valid JSON values. E.g. 1e1000 is converted to Infinity.

@Jake 2016-01-13 08:40:08

python does not support non-ascii

@pnd 2016-02-18 11:49:29

Changed in Python 3.5: Output now same order as Input. Use --sort-keys to sort keys alphabetically. In response to comment by @ChrisNash.

@arete 2016-06-21 22:54:03

If you're on macOS and you have some json on the clipboard that you want formatted pbpaste | python -m json.tool | pbcopy.

@asgs 2016-11-18 06:24:42

Amazing! Thanks for sharing this. Also, in case you have passed in the "-i" option to cURL, it won't be able to pretty print the json as you have now got HTTP headers as well.

@Jack 2017-08-07 14:09:24

What if I want to cat it using python -m json.tool /path.json?

@12431234123412341234123 2017-08-08 12:46:15

Is there a way to format the brackets in a better way? (Use same column for the left bracket and the corresponding right bracket)

@Loftx 2017-12-21 11:35:36

@ClintEastwood - the curl -s option will supress the output e.g. curl -s http://my_url/ | python -m json.tool Should just print the JSON.

@Lightness Races in Orbit 2018-02-16 00:41:41

This effectively just answers how to do it in Python, or on the web. The letter of the question seems to be satisfied, but I don't think the spirit of it has been at all. 3,551 upvotes seems like a gross overreaction.

@Wakan Tanka 2019-02-20 13:42:35

which module is required to be installed? I get: /usr/bin/python: No module named json.module

@anarchist912 2019-09-30 12:18:56

@ClintEastwood To suppress the progress report / bar of curl, just pass the silent flag: curl -s

@Alex M 2019-10-18 17:06:26

is this the highest voted unaccepted answer of all time

@tanius 2019-10-22 23:53:31

The technique from this answer, for all .json files in your current directory: for file in *.json; do python -m json.tool $file > ${file/.json/.pretty.json}; done

@Finn Årup Nielsen 2019-10-29 12:52:48

json.tool does not work well for large files. There is a fp.read() in there somewhere reading the entire JSON file.

@peak 2018-02-25 13:50:32

jj is super-fast, can handle ginormous JSON documents economically, does not mess with valid JSON numbers, and is easy to use, e.g.

jj -p # for reading from STDIN

or

jj -p -i input.json

It is (2018) still quite new so maybe it won’t handle invalid JSON the way you expect, but it is easy to install on major platforms.

@fangxing 2017-10-27 06:41:27

Use Ruby in one line:

echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"

And you can set an alias for this:

alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

Then you can use it more conveniently

echo '{"test":1,"test2":2}' | to_j

{
  "test": 1,
  "test2": 2
}

And if you want display JSON with color, your can install awesome_print,

gem install awesome_print

then

alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""

Try it!

echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j

Enter image description here

@Olexandr Minzak 2017-05-18 15:47:04

It is not too simple with a native way with the jq tools.

For example:

cat xxx | jq .

@peak 2017-10-20 07:23:37

WARNING: jq encodes numbers as IEEE 754 64-bit floats, and thus their representation is likely to change. The precision of very small and very large numbers is likely to be lost. To check whether your favorite pretty-printer has the same issue, try this value: 1e1000.

@michael 2017-12-01 07:33:36

or simply: jq . file.json ; but also cat file.json | jq (without the filter .) also works. (on ubuntu/linux; ymmv across platforms)

@Aidan Melen 2017-02-20 04:37:46

https://github.com/aidanmelen/json_pretty_print

from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import json
import jsonschema

def _validate(data):
    schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
    try:
        jsonschema.validate(data, schema,
                            format_checker=jsonschema.FormatChecker())
    except jsonschema.exceptions.ValidationError as ve:
        sys.stderr.write("Whoops, the data you provided does not seem to be " \
        "valid JSON.\n{}".format(ve))

def pprint(data, python_obj=False, **kwargs):
    _validate(data)
    kwargs["indent"] = kwargs.get("indent", 4)
    pretty_data = json.dumps(data, **kwargs)
    if python_obj:
        print(pretty_data)
    else:
       repls = (("u'",'"'),
                ("'",'"'),
                ("None",'null'),
                ("True",'true'),
                ("False",'false'))
    print(reduce(lambda a, kv: a.replace(*kv), repls, pretty_data))

@Tadej 2017-02-02 21:23:17

That's how I do it:

curl yourUri | json_pp

It shortens the code and gets the job done.

@jonathanjo 2019-06-21 13:22:46

Ubuntu server: If you have production machines with very restricted installations, this might be the best choice as it is installed by default under a specific name. Python is often installed in different ways (eg python3, python or not at all) depending on the version.

@Nikhil Ranjan 2017-02-01 09:31:33

If you have Node.js installed you can create one on your own with one line of code. Create a file pretty:

> vim pretty

#!/usr/bin/env node

console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));

Add execute permission:

> chmod +x pretty

> ./pretty '{"foo": "lorem", "bar": "ipsum"}'

Or if your JSON is in a file:

#!/usr/bin/env node

console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));

> ./pretty file.json

@Nikhil Ranjan 2017-05-30 17:33:09

process.stdin.resume(); var input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { console.log(JSON.stringify(JSON.parse(input), null, 2)); });

@adius 2015-11-14 09:58:12

For Node.js you can also use the "util" module. It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk =>  {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"

@Shubham Chaudhary 2015-08-27 10:09:30

Pygmentize

I combine Python's json.tool with pygmentize:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

There are some alternatives to pygmentize which are listed in my this answer.

Here is a live demo:

Demo

@J P 2015-11-23 10:13:46

Sometimes one needs to use pygmentize -l json to get colourfication.

@jan 2018-01-05 11:56:02

Install with apt package python-pygments, i.e. apt-get install python-pygments

@jordelver 2013-05-21 09:18:49

UPDATE I'm using jq now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.

jsonpp is a very nice command line JSON pretty printer.

From the README:

Pretty print web service responses like so:

curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp

and make beautiful the files running around on your disk:

jsonpp data/long_malformed.json

If you're on Mac OS X, you can brew install jsonpp. If not, you can simply copy the binary to somewhere in your $PATH.

@volker 2015-04-28 19:27:19

I tried jsonpp (used in the past successful) against a huge file (>60MB). I stopped it after 5min. I piped it into python -mjson.tool (from other answer here) and it took 10-20sec...

@jordelver 2015-04-28 21:43:07

60MB of JSON? Wow! I don't typically deal with files that big but useful to know. Thanks.

@davidpricedev 2016-07-29 11:24:14

On my ubuntu box I have a json_pp - which does format json nicely, although despite the similarity in naming, I believe this to be an entirely different project from the jsonpp mentioned here

@Johann Philipp Strathausen 2013-01-29 12:23:49

Try pjson. It has colors!

echo '{"json":"obj"} | pjson

Install it with pip:

⚡ pip install pjson

And then pipe any JSON content to pjson.

@Kristjan Adojaan 2013-11-22 12:47:22

It requires python-pip (sudo apt-get install python-pip) and then (sudo pip install pjson) The great advantage are colours!

@Kristjan Adojaan 2013-11-22 12:54:36

The disadvantage is it is not possible to grep coloured output.

@Roberto 2012-11-16 10:24:15

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
}

@Dave Dopson 2012-05-01 16:48:57

I wrote a tool that has one of the best "smart whitespace" formatters available. It produces more readable and less verbose output than most of the other options here.

underscore-cli

This is what "smart whitespace" looks like:

I may be a bit biased, but it's an awesome tool for printing and manipulating JSON data from the command-line. It's super-friendly to use and has extensive command-line help/documentation. It's a Swiss Army knife that I use for 1001 different small tasks that would be surprisingly annoying to do any other way.

Latest use-case: Chrome, Dev console, Network tab, export all as HAR file, "cat site.har | underscore select '.url' --outfmt text | grep mydomain"; now I have a chronologically ordered list of all URL fetches made during the loading of my company's site.

Pretty printing is easy:

underscore -i data.json print

Same thing:

cat data.json | underscore print

Same thing, more explicit:

cat data.json | underscore print --outfmt pretty

This tool is my current passion project, so if you have any feature requests, there is a good chance I'll address them.

@Gal Bracha 2013-11-20 18:42:14

I also updated my ~/.bash_profile to have the following line: alias underscor='underscore print --outfmt pretty' now I can just do curl example.com/result.json | underscor and still use underscore for other formatting

@Maxim Ponomarev 2015-01-20 09:44:21

Thanks Dave! Tool is good! alias pretty-json="underrsore pretty" and curl output pleasing an eye

@tiurin 2015-01-24 12:18:57

Great formatting tool, just one note: forwarding output to a file (either with -o option or with > ) works only with underscore print. underscore pretty saves a file with color formatting signs being inserted, smth like: [32m, [33m, [39m along with some non-printable before each of them, which makes JSON not valid. However, underscore print alone doesn't add anything to a file and does its formatting job perfectly.

@Bluu 2015-02-27 00:37:21

I love jq but this worked great for my "JSON" that didn't have double quoted keys.

@mycargus 2015-05-14 02:37:14

@DaveDopson thanks for the great tool!! Gonna try using it alongside jsonselect.org/#tryit ...

@mysterlune 2016-01-19 19:32:23

Also, using npm (use creationix/nvm :) ) to install, because it should be global: npm install -g underscore-cli ... then in .bash_profile: alias json='underscore print --color' ... and use like: cat some.json | json Underscore-CLI is really great and easy to integrate into your development environment.

@numan salati 2011-12-08 21:35:43

Here is how to do it with Groovy script.

Create a Groovy script, let's say "pretty-print"

#!/usr/bin/env groovy

import groovy.json.JsonOutput

System.in.withReader { println JsonOutput.prettyPrint(it.readLine()) }

Make script executable:

chmod +x pretty-print

Now from the command line,

echo '{"foo": "lorem", "bar": "ipsum"}' | ./pretty-print

@MarkHu 2018-01-19 02:10:36

As much as I love Groovy, it isn't a great fit for little scripts like this due to the overhead of the JVM. My informal measurements show jq approximately 50x faster.

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] Can comments be used in JSON?

  • 2008-10-28 20:39:03
  • Michael Gundlach
  • 2380971 View
  • 7736 Score
  • 53 Answer
  • Tags:   json comments

18 Answered Questions

[SOLVED] In the shell, what does " 2>&1 " mean?

  • 2009-05-03 22:57:00
  • Tristan Havelick
  • 1134899 View
  • 2331 Score
  • 18 Answer
  • Tags:   bash shell unix redirect

8 Answered Questions

[SOLVED] How to pretty print XML from the command line?

13 Answered Questions

[SOLVED] How to prettyprint a JSON file?

24 Answered Questions

[SOLVED] Pretty-Printing JSON with PHP

  • 2011-05-19 05:08:29
  • Zach Rattner
  • 542948 View
  • 594 Score
  • 24 Answer
  • Tags:   php json pretty-print

35 Answered Questions

[SOLVED] How can I check if a directory exists in a Bash shell script?

  • 2008-09-12 20:06:25
  • Grundlefleck
  • 2818430 View
  • 3767 Score
  • 35 Answer
  • Tags:   bash shell unix posix

24 Answered Questions

[SOLVED] How do I POST JSON data with cURL?

41 Answered Questions

[SOLVED] How do I format a Microsoft JSON date?

18 Answered Questions

[SOLVED] How to "pretty" format JSON output in Ruby on Rails

24 Answered Questions

[SOLVED] pretty-print JSON using JavaScript

Sponsored Content