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"
}
When you have node installed on your system the following works.
echo '{"test":1,"test2":2}' | npx json
{
"test": 1,
"test2": 2
}
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
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 ))"
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
Mar 9, 2020 at 16:22
yajl
is very nice, in my experience. I use its json_reformat
command to pretty-print .json
files in vim
by putting the following line in my .vimrc
:
autocmd FileType json setlocal equalprg=json_reformat
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"
}
TL;DR: for performances, use jj -p < my.json
.
I took some solutions here and benchmarked them with the next dummy script:
function bench {
time (
for i in {1..1000}; do
echo '{ "foo" : { "bar": { "dolorem" : "ipsum", "quia" : { "dolor" : "sit"} } } }' \
| $@ > /dev/null
done
)
}
Here's the result on my mac (32 GB, Apple M1 Max, YMMV):
bench python -m json.tool
# 8.39s user 12.31s system 42% cpu 48.536 total
bench jq
# 13.12s user 1.28s system 87% cpu 16.535 total
bench bat -p -l json # NOTE: only syntax colorisation.
# 1.87s user 1.47s system 66% cpu 5.024 total
bench jj -p
# 1.94s user 2.44s system 57% cpu 7.591 total
bench xidel -s - -e '$json' --printed-json-format=pretty
# 4.32s user 1.89s system 76% cpu 8.101 total
Thanks @peak and your answer for this discovery of jj!
brew install jq bat tidwall/jj/jj xidel
, (2.) copy and paste the function block, (3.) copy and paste the bench block, (4.) edit this post with your configuration (about my mac). Also please, no need to be complacent, I get the gist...
Mar 3, 2022 at 16:41
brew install xidel --head
and feel the svn pain). However I'll have to admit, it is fast (5s
, beats jj). I'd still not advise it: the installation process is heavy, and the the build is yet to be official... DISCLAIMER: I'll stop editing this post from now on. I've added enough information in the comment for anyone else to do it, so please do! I'm not paid more than you to do that.
Mar 4, 2022 at 12:37
I'm using httpie
$ pip install httpie
And you can use it like this
$ http PUT localhost:8001/api/v1/ports/my
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 93
Content-Type: application/json
Date: Fri, 06 Mar 2015 02:46:41 GMT
Server: nginx/1.4.6 (Ubuntu)
X-Powered-By: HHVM/3.5.1
{
"data": [],
"message": "Failed to manage ports in 'my'. Request body is empty",
"success": false
}
The PHP version, if you have PHP >= 5.4.
alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json
echo '{"a":1,"b":2}' | php -r 'echo json_encode(json_decode(fgets(STDIN)), JSON_PRETTY_PRINT)."\n";'
Mar 5, 2016 at 13:42
printf '{\n"a":1,\n"b":2\n}' | php -r 'echo json_encode(json_decode(file_get_contents("php://stdin")), JSON_PRETTY_PRINT) . PHP_EOL;'
Feb 23, 2017 at 1:35
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";'
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}))}}))"
The tool ydump
is a JSON pretty-printer:
$ ydump my_data.json
{
"foo": "lorem",
"bar": "ipsum"
}
Or you can pipe in the JSON:
$ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump
{
"foo": "lorem",
"bar": "ipsum"
}
This is probably the shortest solution apart from using the jq
tool.
This tool is part of the yojson
library for OCaml, and is documented here.
On Debian and derivatives, the package libyojson-ocaml-dev
contains this tool. Alternatively, yojson
can be installed via OPAM.
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
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
jq
approximately 50x faster.
I've came up with this solution: https://calbertts.medium.com/unix-pipelines-with-curl-requests-and-serverless-functions-e21117ae4c65
# this in your bash profile
jsonprettify() {
curl -Ss -X POST -H "Content-Type: text/plain" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@
}
echo '{"prop": true, "key": [1,2]}' | jsonprettify 4
# {
# "prop": true,
# "key": [
# 1,
# 2
# ]
# }
There's no need to install anything, if you have an internet connection and cURL installed, you can use this function.
Are you in another host where you can't install anything, this would be a perfect solution to that issue.
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
gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty
This method also "Detects HTTP response/headers, prints them untouched, and skips to the body (for use with `curl -i')".
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))
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.
Here is a Groovy one-liner:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
You can use Prettier to do this.
npx prettier <JSON file>
should print a prettified version of the JSON in the given file, while npx prettier --write <JSON file>
will overwrite the given JSON file with prettified JSON.
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}'
echo '{ "foo": "lorem", "bar": "ipsum" }' | curl -XPOST https://jsonprettyprint.org/api -d @-
May 29, 2017 at 13:13
Also be sure to check out JSONFUI: A command line JSON viewer that supports folding
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.
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 -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
"foo": "lorem",
"bar": "ipsum"
}
or:
$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
"foo": "lorem",
"bar": "ipsum"
}
If you want to visualize json log at console you can use munia-pretty-json
npm install -g munia-pretty-json
Your json data (app-log.json)
{"time":"2021-06-09T02:50:22Z","level":"info","message":"Log for pretty JSON","module":"init","hostip":"192.168.0.138","pid":123}
{"time":"2021-06-09T03:27:43Z","level":"warn","message":"Here is warning message","module":"send-message","hostip":"192.168.0.138","pid":123}
Run the command:
munia-pretty-json app-log.json
Here is readable output on console:
You can format the output with the template. The default template is '{time} {level -c} {message}'
Using template:
munia-pretty-json -t '{module -c} - {level} - {message}' app-log.json
Output:
Agree about jq
. You can add the following function to your $HOME/.bashrc
:
jqless () {
args=$1
shift
jq --color-output . $args "$@" | less --raw-control-chars
}
This allows an arbitrary number of input JSON files.
yq can be used to pretty print JSON
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json
It has an option to define the indent
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --indent 3
You can choose between coloured and monochrome output
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --colors
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --no-colors
json
library, but I added pygments as well to get syntax highlighting.