Sunday 24 November 2019

python - How do I write JSON data to a file?



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?


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)

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...