How to transfer JSON data to a file with Python

Asked 2 years ago, Updated 2 years ago, 37 views

You want to write the variable data that stores JSON data in a text file.

I wrote it down like a normal file, and there's an error, so why is that?

obj = open('data.txt', 'wb')
obj.write(data)
obj.close

TypeError: must be string or buffer, not dict

json python

2022-09-21 20:52

1 Answers

There is no problem opening the file.

JSON data is dict type, so you need to JSON-code to write it.

#Python 2 and 3 can be used
import json
with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)
Available in #Python 2.x

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
    f.write(unicode(json.dumps(data, ensure_ascii=False)))
Available in #Python 3.x

import json
with open('data.txt', 'w') as f:
  json.dump(data, f, ensure_ascii=False)


2022-09-21 20:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.