5

Here is some code of mine, I'm trying to convert a dictionary to json having Persian characters but I get question marks instead of characters. My dictionary looks like this:

bycommunity("0": [{"60357": "این یک پیام است"}] )

with open('data.json', 'wb') as f:
f.write(json.dumps(bycommunity).encode("utf-8"))

the result is :

{"0": [{"60357": "?????? ??? ??? ???? ???????? ??????"}]} 
Dale K
  • 25,246
  • 15
  • 42
  • 71

2 Answers2

7
data = {"0": [{"60357": "این یک پیام است"}]} 
with open('data.json', 'w') as f:
  json.dump(data, f, ensure_ascii=False)

and also check this Answer for more details

Dale K
  • 25,246
  • 15
  • 42
  • 71
  • 1
    Please, don't name the variable `dict` and thus hide the built-in `dict`. Name it e.g. `data`, or whatever. – zvone Feb 03 '19 at 09:05
  • You also don’t need to explicitly close a file that’s opened using `with`. And you can use `json.dump(data, f, ensure_ascii=True)` to negate having to use `jsonData` variable. – Jab Feb 03 '19 at 09:09
  • It helps to explain the change you've made as opposed to just correct it. – Dale K Feb 04 '19 at 02:56
2
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
        jsonf.write(json.dumps(data, ensure_ascii=False, indent=4))
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27