user1530318 user1530318 - 5 months ago 20
JSON Question

How do I write JSON data to a file in Python?

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 am receiving the error:

TypeError: must be string or buffer, not dict


How to fix this?

Answer

You forgot the actual JSON part - data is a dictionary and not yet JSON-encoded. Write it like this:

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

Note: Works on both 3.x and 2.x .