Martin Eldredge
Martin Eldredge

Reputation: 33

How to format JSON style text using python?

I wrote a program to convert KML to GeoJSON. But, when I look at the output files, they are written without whitespace, making them very hard to read.

I tried to use the json module like so: file = json.load("<filename>") But it returned the following:

File "/usr/lib/python3.6/json/__init__.py", line 296, in load
    return loads(fp.read())
AttributeError: 'str' has no attribute 'read'

Upvotes: 2

Views: 218

Answers (1)

chepner
chepner

Reputation: 531888

load takes a file object, not a file name.

with open("filename") as fh:
    d = json.load(fh)

Once you've parsed it, you can dump it again, but formatted a bit more nicely

with open("formatted-filename.json", "w") as fh:
    json.dump(d, fh, indent=4)

Upvotes: 2

Related Questions