arrays - Python how to save dictionary with cyrillic symbols into json file -
#!/usr/bin/env python # -*- coding: utf-8 -*- import json d = {'a':'текст', 'b':{ 'a':'текст2', 'b':'текст3' }} print(d) w = open('log', 'w') json.dump(d,w, ensure_ascii=false) w.close()
it gives me: unicodeencodeerror: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
post full traceback, error coming print statement when fails decode dictionary object. reason print statement cannot decode contents if have cyrillic text in it.
here how save json dictionary contains cyrillics:
mydictionary = {'a':'текст'} filename = "myoutfile" open(filename, 'w') jsonfile: json.dump(mydictionary, jsonfile, ensure_ascii=false)
the trick reading in json dictionary , doing things it.
to read in json dictionary:
with open(filename, 'r') jsonfile: newdictonary = json.load(jsonfile)
now when @ dictionary, word 'текст' looks (encoded) '\u0442\u0435\u043a\u0441\u0442'. need decode using encode('utf-8'):
for key, value in newdictionary.iteritems(): print value.encode('utf-8')
same goes lists if cyrillic text stored there:
for f in value: print f.encode('utf-8') # or if plan use val somewhere else: f = f.encode('utf-8')
Comments
Post a Comment