75

Is there an editor or tool for Linux command line to format JSON data?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Siva
  • 1,265
  • 4
  • 17
  • 24

4 Answers4

106
 alias pp='python -mjson.tool'
 pp mydata.json

From the first link in the accepted answer: http://ruslanspivak.com/2010/10/12/pretty-print-json-from-the-command-line/

tjb
  • 11,480
  • 9
  • 70
  • 91
87

jq is a lightweight and flexible command-line JSON processor.

http://stedolan.github.io/jq/

jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

jq is written in portable C, and it has zero runtime dependencies. You can download a single binary, scp it to a far away machine, and expect it to work.

here
  • 2,790
  • 25
  • 30
  • 9
    To me this solution seems the best: easy to install, and output keeps the order of attributes from input - this might be sometime very practical when authoring documentation as it supports better readability. Typical use: `$ jq . data.json` (mind the dot after the `jq`). – Jan Vlcinsky Jun 24 '15 at 20:40
  • 1
    jq is superb. note that this will not work. ```jq . data.json > data.json```. which will overwrite itself. export to a temp file and overwrite existing. – mirageglobe Apr 28 '19 at 20:01
  • 4
    Indeed jq is superb. Once you have jq installed, in Vim you can paste any JSON into a new buffer and run `:%!jq '.'` this pretty prints the JSON in the buffer. Source: [Vim: prettify JSON](https://remarkablemark.org/blog/2018/02/28/vim-beautify-json/) – icc97 Sep 08 '20 at 16:22
20

On Ubuntu jsonlint is provided by apt:python3-demjson

Usage:

$ sudo apt install -y python3-demjson
$ jsonlint -f input.json > output.json
gliptak
  • 3,592
  • 2
  • 29
  • 61
  • 1
    Great for when the JSON you're looking at doesn't conform to the spec. Other tools (`jq`, the Python `json` module) require completely conformant JSON for them to work. – pR0Ps Jan 25 '16 at 16:41
  • 5
    It appears that in current packages the command installed with the "python-demjson" package is "jsonlint-py" instead of "jsonlint". – vorburger Jan 14 '17 at 13:08
  • The apt package appears to be called `python3-demjson` by now. The command installed with this package is still called "jsonlint" however. – cherrywoods Jan 02 '22 at 14:46
9

Add to vimrc:

" Format JSON data
map <C-F6> :%!python -m json.tool<CR>

And you can use the shortcut CTRL+F6 to format json data


Or just under vim's command mode:

%!python -m json.tool
Yaohui.W
  • 328
  • 3
  • 15
  • If you're using vim you can: `au FileType json set equalprg=python\ -m\ json.tool` and format with `=`. – Tanath Mar 05 '19 at 21:00