Python – How to write JSON data to a file

jsonpython

I have JSON data stored in the variable data.

I want to write this to a text file for testing so I don't have to grab the data from the server each time.

Currently, I am trying this:

obj = open('data.txt', 'wb')
obj.write(data)
obj.close

And I am receiving this error:

TypeError: must be string or buffer, not dict

How to fix this?

Best Answer

You forgot the actual JSON part - data is a dictionary and not yet JSON-encoded. Write it like this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file with

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)