Skip to main content

How to pretty-print JSON script?


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: Tips4allCCNA FINAL EXAM

Comments

  1. With python you can just do

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

    ReplyDelete
  2. I use JSON.stringify to pretty-print JSON.

    Examples:

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

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

    ReplyDelete
  3. The JSON Ruby Gem is bundled with a shell script to prettify JSON:

    sudo gem install json
    echo '{ "foo": "bar" }' | prettify_json.rb

    ReplyDelete
  4. Thanks to J.F. Sebastian's very helpful pointers, here's a slightly enhanced script I've come up with:

    #!/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))

    ReplyDelete
  5. On *nix, reading from stdin and writing to stdout works better:

    #!/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".

    ReplyDelete
  6. http://jsonlint.com has a nice validator/formatter if you not looking for a programmatic way of doing it.

    ReplyDelete
  7. I use jshon - to do exactly what you're describing, just run:

    echo $COMPACTED_JSON_TEXT | jshon


    You can also pass arguments to transform the json data.

    ReplyDelete
  8. for the peeps looking for a quick online thingy:
    http://www.shell-tools.net/index.php?op=json%5Fformat

    ReplyDelete
  9. Or, with Ruby:

    echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'

    ReplyDelete
  10. 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.

    ReplyDelete
  11. i usually just do

    echo '{"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"]'

    ReplyDelete
  12. with perl, use CPAN module JSON::XS.

    it 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

    ReplyDelete
  13. $ echo '{ "foo": "lorem", "bar": "ipsum" }' \
    > | 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"
    }

    ReplyDelete
  14. Check out Jazor. It's a simple command line JSON parser written in Ruby.

    gem install jazor
    jazor --help

    ReplyDelete
  15. There is TidyJSON it's C#, so maybe you can get it to compile with Mono, and working on *nix. No guarantees though, sorry.

    ReplyDelete
  16. yajl 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:

    autocmd FileType json set equalprg=json_reformat

    ReplyDelete
  17. Maybe pretty-print.heroku.com is going to be of some help to you.

    ReplyDelete
  18. I 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:

    sudo 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

    ReplyDelete
  19. $ sudo apt-get install edit-json
    $ prettify_json myfile.json

    ReplyDelete
  20. You can also look at Cerny.js which I stumbled upon while looking for a good solution.

    ReplyDelete
  21. Here is how to do it with groovy script.

    Create 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

    ReplyDelete
  22. 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.

    $ echo '{"a": 1, "b": 2}' | json-liner
    /%a 1
    /%b 2
    $ echo '["foo", "bar", "baz"]' | json-liner
    /@0 foo
    /@1 bar
    /@2 baz

    ReplyDelete
  23. 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:


    Command 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.

    ReplyDelete
  24. Let me jump on the dogpile with one more suggestion:

    underscore-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.

    ReplyDelete
  25. 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:


    perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'

    ReplyDelete
  26. With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:

    [pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
    {
    "bar" : "ipsum",
    "foo" : "lorem"
    }

    ReplyDelete
  27. Another way to do it with any version of Python that can use the json module is shown here.

    ReplyDelete
  28. with javascript / nodeJS:

    take 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.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex