0 votes
1 view
in Python by (47.8k 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 (107k 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.8k points)
+2 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Dec 12, 2020 in Python by laddulakshana (12.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...