See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

How do I write JSON data to a file?

General Tech QA/Testing
Max. 2000 characters

Katie George


( 6 months ago )

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

And am receiving the error:

TypeError: must be string or buffer, not dict

How to fix this?

Nageshwer Reddy


( 6 months ago )

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

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

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

what's your interest