4

There is a way to pretty-print valid JSON with Python : How can I pretty-print JSON in (unix) shell script?

However jsonlint.com pretty-prints JSON even if there is something wrong.

I want to do that, and I'm using Python. Does anyone know a script that does it ?

Thanks :)

Community
  • 1
  • 1
Myna
  • 569
  • 2
  • 10
  • 24
  • 5
    Consider inspecting https://github.com/zaach/jsonlint which powers jsonlint.com for insights. – 9000 Jun 12 '12 at 15:51
  • 2
    I have considered using this repo, but I'm required to use tools that run with Python only ... But that's exactly what i need though. – Myna Jun 12 '12 at 16:10

4 Answers4

2

@kelw has already pointed out demjson, which works well for slightly invalid JSON. For data that's even less JSON compliant I've written barely_json:

from barely_json import parse
from pprint import pprint

invalid_json = '[no, , {complete: yes}]'
data = parse(invalid_json)
pprint(data)
Community
  • 1
  • 1
Florian Brucker
  • 9,621
  • 3
  • 48
  • 81
1

You can use demjson module either in your own script or jsonlint.py tool it prvides

keiw
  • 1,260
  • 1
  • 9
  • 13
1

Try jsbeautifier library for beautifying JavaScript. It works because JSON is "almost" subset of JavaScript.

import json
import jsbeautifier

invalid_json = '{"hello": "world",}'

json.loads(invalid_json)
# ValueError: Expecting property name: line 4 column 1 (char 25)

jsbeautifier.beautify(invalid_json)
# '{\n    "hello": "world",\n}'
kakty3
  • 1,149
  • 1
  • 9
  • 12
0

There's a built-in way to do it with Python:

python -m json.tool myfile.json
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 3
    If there is an error, it says where it is, but doesn't print back what I have. I'm interested in pretty-printing even if it's invalid. Any solution ? – Myna Jun 12 '12 at 15:58
  • Please consider my answer below – keiw Nov 30 '12 at 16:39