Myna
Myna

Reputation: 559

Pretty printing invalid JSON with Python

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 :)

Upvotes: 4

Views: 1795

Answers (4)

kakty3
kakty3

Reputation: 1239

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}'

Upvotes: 1

Florian Brucker
Florian Brucker

Reputation: 10355

@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)

Upvotes: 2

keiw
keiw

Reputation: 1410

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599620

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

python -m json.tool myfile.json

Upvotes: 0

Related Questions