An utility to reformat JSON-documents with newlines and indention according to the document structure (or my personal taste if you like).
_ jsonprettify _ follows the convention by which the commas a are place before the next item instead of after the previous item. This makes it easier to spot missing commas and incorrect document structure in general.
If you are looking for conventional formatting consider prettify_json.rb
supplied with the json ruby gem.
For example: jsonprettify < package.json
reformats the file
package.json and prints it out to stout. For in-place formatting
it is possible to use the -i
and -o
specifying the same file,
e.g. jsonprettify -i package.json -o package.json
.
-
--compact
of-c
will use the standardJSON.stringify
command in node. This will result in a compact representation without newlines and spaces. -
if '-i' is not specified, stdin is used
-
same as above with '-o' and stdout
There are more options. Invoke jsonprettify --help
for the complete list of available options.
An example in coffee-script would look like:
jsonprettify = require 'jsonprettify'
pretty_json = jsonprettify.json2prettyjson '{"someObject": {"somekey":"somevalue","boolkey":true},"someArray":["abc",3,1,2,true,false]}'
and if we output pretty_json
we would get:
{ "someObject" :
{ "somekey" : "somevalue"
, "boolkey" : true
}
, "someArray" :
[ "abc"
, 3
, 1
, 2
, true
, false
]
}
json2prettyjson accepts an additional option argument, .e.g:
opts =
{ "indent" : " "
, "sort" : true
}
Note that the order has changed to be lexicographically sorted. However, depending on the input it might be necessary prettify several times to actually get the correct lexicographic order.
{ "someArray" :
[ 1
, 2
, 3
, "abc"
, false
, true
]
, "someObject" :
{ "boolkey" : true
, "somekey" : "somevalue"
}
}
Note also that sorting arrays might not be a good idea in some cases.