6

I've the json data in below format and I'm trying to store it in JSON file but it's storing in encoded form in data.json file

data= {"a": "{0}さんではないですか?"}
    with open('data.json', 'w') as fp:
        fp.write(json.dumps(data).encode("utf8"))

data.json

{"a": "{0}\u3055\u3093\u3067\u306f\u306a\u3044\u3067\u3059\u304b\uff1f"}

I want data.json to be in this format

{"a": "{0}さんではないですか?"}

I tried encoding it and then putting it in json file, no success.. can anybody tell what I'm doing wrong here and what is the right way?

Gaurav Sharma
  • 411
  • 7
  • 22

2 Answers2

10

Try using json.dumps(s, ensure_ascii=False).

Javier
  • 2,752
  • 15
  • 30
  • working, thanks another question what if I have data like {u'a: u'\u4e0d\u662f{0}?'} and this I would like to store in data.json file? I tried above method but it's giving me below error UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-24: ordinal not in range(128) – Gaurav Sharma May 12 '18 at 15:09
  • The other answer, answers that. – Javier May 12 '18 at 15:38
2

If you encode it you should also open the file as a byte array with wb. Because you are using utf8 instead of ascii include ensure_ascii=False in the json.dumps()

Give this a try

import json

data= {"a": "{0}さんではないですか?"}
with open('data.json', 'wb') as fp:
    fp.write(json.dumps(data, ensure_ascii=False).encode("utf8"))

data = {"a": "{0}さんではないですか?"} and

data = {"a": "{0}\u3055\u3093\u3067\u306f\u306a\u3044\u3067\u3059\u304b\uff1f"}

Both gets stored as {"a": "{0}さんではないですか?"} in the json file.

ktzr
  • 1,625
  • 1
  • 11
  • 25