Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

In your code, you did not mention the actual JSON part - data which is a dictionary and not yet JSON-encoded. So in Python, you can write it like this for maximum compatibility:-

import json 

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

     json.dump(data, outfile)

In Python 3 you can write it as follows:-

import json

with open('data.json', 'w', encoding='utf-8') as outfile:

     json.dump(data, outfile, ensure_ascii=False, indent=2)

Related questions

0 votes
2 answers
asked Jul 3, 2019 in Python by Sammy (47.6k points)
+2 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Dec 12, 2020 in Python by laddulakshana (16.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...