Is there a (*nix) command-line 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"
}
Thanks!
Source: Tips4all
With python you can just do
ReplyDeleteecho '{"foo": "lorem", "bar": "ipsum"}' | python -mjson.tool
I use JSON.stringify to pretty-print JSON.
ReplyDeleteExamples:
JSON.stringify({ foo: "lorem", bar: "ipsum" }, null, 4);
JSON.stringify({ foo: "lorem", bar: "ipsum" }, null, '\t');
The JSON Ruby Gem is bundled with a shell script to prettify JSON:
ReplyDeletesudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
Thanks to J.F. Sebastian's very helpful pointers, here's a slightly enhanced script I've come up with:
ReplyDelete#!/usr/bin/python
"""
Convert JSON data to human-readable form.
Usage:
prettyJSON.py inputFile [outputFile]
"""
import sys
import simplejson as json
def main(args):
try:
inputFile = open(args[1])
input = json.load(inputFile)
inputFile.close()
except IndexError:
usage()
return False
if len(args) < 3:
print json.dumps(input, sort_keys = False, indent = 4)
else:
outputFile = open(args[2], "w")
json.dump(input, outputFile, sort_keys = False, indent = 4)
outputFile.close()
return True
def usage():
print __doc__
if __name__ == "__main__":
sys.exit(not main(sys.argv))
On *nix, reading from stdin and writing to stdout works better:
ReplyDelete#!/usr/bin/env python
"""
Convert JSON data to human-readable form.
(Reads from stdin and writes to stdout)
"""
import sys
import simplejson as json
print json.dumps(json.loads(sys.stdin.read()), indent=4)
sys.exit(0)
Put this in a file (I named mine "prettyJSON" after AnC's answer) in your PATH and chmod +x it, and you're good to go.
Depending on the version of Python you have installed, you may need to replace "import simplejson as json" with "import json".
http://jsonlint.com has a nice validator/formatter if you not looking for a programmatic way of doing it.
ReplyDeleteI use jshon - to do exactly what you're describing, just run:
ReplyDeleteecho $COMPACTED_JSON_TEXT | jshon
You can also pass arguments to transform the json data.
for the peeps looking for a quick online thingy:
ReplyDeletehttp://www.shell-tools.net/index.php?op=json%5Fformat
Or, with Ruby:
ReplyDeleteecho '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
If you use npm and nodejs, you can do npm install json-command and then pipe the command through json. Do json -h to get all the options. It can also pull out specific fields and colorize the output with -i.
ReplyDeletei usually just do
ReplyDeleteecho '{"test":1,"test2":2}' | python -mjson.tool
and to read some data :
echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'
with perl, use CPAN module JSON::XS.
ReplyDeleteit installs a command line tool "json_xs"
Validate:
json_xs -t null < myfile.json
Prettify the JSON file src.json to pretty.json.
< src.json json_xs > pretty.json
$ echo '{ "foo": "lorem", "bar": "ipsum" }' \
ReplyDelete> | python -c'import fileinput, json;
> print(json.dumps(json.loads("".join(fileinput.input())),
> sort_keys=True, indent=4))'
{
"bar": "ipsum",
"foo": "lorem"
}
NOTE: It is not the way to do it.
The same in Perl:
$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}),
> {pretty=>1})'
{
"bar" : "ipsum",
"foo" : "lorem"
}
Check out Jazor. It's a simple command line JSON parser written in Ruby.
ReplyDeletegem install jazor
jazor --help
There is TidyJSON it's C#, so maybe you can get it to compile with Mono, and working on *nix. No guarantees though, sorry.
ReplyDeleteyajl is very nice, in my experience. I use its reformat_json command to pretty-print .json files in vim by putting the following line in my .vimrc:
ReplyDeleteautocmd FileType json set equalprg=json_reformat
Maybe pretty-print.heroku.com is going to be of some help to you.
ReplyDeleteI recommend using the json_xs command line utility which is included in the JSON::XS perl module. JSON::XS is a perl module for serializing/deserializing JSON, on a Debian or Ubuntu machine you can install it like this:
ReplyDeletesudo apt-get install libjson-xs-perl
It is obviously also avalible on cpan.
To use it to format json obtained from a url you can use curl or wget like this:
$ curl -s http://page.that.serves.json.com/json/ | json_xs
or this:
$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
and to format json contained in a file you can do this:
$ json_xs < file-full-of.json
$ sudo apt-get install edit-json
ReplyDelete$ prettify_json myfile.json
You can also look at Cerny.js which I stumbled upon while looking for a good solution.
ReplyDeleteHere is how to do it with groovy script.
ReplyDeleteCreate a groovy script, lets 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 command line,
echo '{"foo": "lorem", "bar": "ipsum"}' | ./pretty-print
I'm the author of json-liner. It's a command line tool to turn JSON into a grep friendly format. Give it a try.
ReplyDelete$ echo '{"a": 1, "b": 2}' | json-liner
/%a 1
/%b 2
$ echo '["foo", "bar", "baz"]' | json-liner
/@0 foo
/@1 bar
/@2 baz
There is a popular online tool called JSONLint. If you cared to read the credits it will lead you to the JSON Lint project on github where you will find out that it is in fact A JSON parser and validator with a CLI. Quote from the readme file:
ReplyDeleteCommand line interface
Install jsonlint with npm to use the command line interface:
npm install jsonlint -g
Validate a file like so:
jsonlint myfile.json
or pipe input into stdin:
cat myfile.json | jsonlint
jsonlint will either report a syntax error with details or pretty
print the source if it is valid.
Let me jump on the dogpile with one more suggestion:
ReplyDeleteunderscore-cli
I wrote it, so 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 comany'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 json-pretty
This tool is my current passion project, so if you have any feature requests, good chance I'll address them.
J.F. Sebastian's solutions didn't work for me in Ubuntu 8.04, here is a modified Perl version that works with the older 1.X JSON library:
ReplyDeleteperl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'
With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:
ReplyDelete[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
"bar" : "ipsum",
"foo" : "lorem"
}
Another way to do it with any version of Python that can use the json module is shown here.
ReplyDeleteJust found jsonpp
ReplyDeletewith javascript / nodeJS:
ReplyDeletetake a look at the vkBeautify.js plugin
http://www.eslinstructor.net/vkbeautify/
which provides pretty printing for both JSON and XML text
it's written in plain javascript, less then 1.5K (minified) and very fast.