ensure_ascii=Falseस्विच का उपयोग करें json.dumps(), फिर मान को UTF-8 में मैन्युअल रूप से एन्कोड करें:
>>> json_string = json.dumps("ברי צקלה", ensure_ascii=False).encode('utf8')
>>> json_string
b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
>>> print(json_string.decode())
"ברי צקלה"
यदि आप किसी फ़ाइल को लिख रहे हैं, json.dump()तो उसका उपयोग करें और उसे एनकोड करने के लिए फ़ाइल ऑब्जेक्ट पर छोड़ दें:
with open('filename', 'w', encoding='utf8') as json_file:
json.dump("ברי צקלה", json_file, ensure_ascii=False)
पायथन 2 के लिए कैवेट
पायथन 2 के लिए, खाते में लेने के लिए कुछ और चेतावनी हैं। यदि आप इसे किसी फ़ाइल में लिख रहे हैं, तो आप एक फ़ाइल ऑब्जेक्ट का निर्माण करने के io.open()बजाय इसका उपयोग कर सकते हैं open()जो आपके लिखते समय यूनिकोड मानों को एनकोड करता है, फिर json.dump()उस फ़ाइल पर लिखने के बजाय इसका उपयोग करें :
with io.open('filename', 'w', encoding='utf8') as json_file:
json.dump(u"ברי צקלה", json_file, ensure_ascii=False)
ध्यान दें कि मॉड्यूल मेंjson एक बग है जहां ensure_ascii=Falseझंडा और वस्तुओं के मिश्रण का उत्पादन कर सकता है । पायथन 2 के लिए समाधान तब है:unicodestr
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(u"ברי צקלה", ensure_ascii=False)
# unicode(data) auto-decodes data to unicode if str
json_file.write(unicode(data))
पायथन 2 में, बाइट स्ट्रिंग्स (प्रकार str) का उपयोग करते समय , UTF-8 को एन्कोड किया गया, यह भी सुनिश्चित करें कि encodingकीवर्ड सेट करें :
>>> d={ 1: "ברי צקלה", 2: u"ברי צקלה" }
>>> d
{1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}
>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
>>> s
u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
>>> json.loads(s)['1']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> json.loads(s)['2']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> print json.loads(s)['1']
ברי צקלה
>>> print json.loads(s)['2']
ברי צקלה