Dror
Dror

Reputation: 13051

Save a python 3.x dictionary to JSON

The solution suggested in this answer allows saving a dict into json. For instance:

import json
with open('data.json', 'wb') as fp:
    json.dump(data, fp)

However, this doesn't work with 3.x. I get the following error:

TypeError: 'str' does not support the buffer interface

According to this answer, the solution is some sort of cast; but I don't manage to do it for a dictionary. What's the right way to save a dict to json using python 3.x?

Upvotes: 3

Views: 1989

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

remove the b:

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

json.dump

The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.

Upvotes: 8

Related Questions