3

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?

Community
  • 1
  • 1
Dror
  • 12,174
  • 21
  • 90
  • 160

1 Answers1

8

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.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Can you please add some reference? Where could I find this solution in the documentation? – Dror Feb 16 '15 at 12:50