The solution to the problem of reading and writing json Chinese ASCII

  • 2020-05-17 05:45:44
  • OfStack

Today, I want to help the front-end write a small background, which is to read the data and then send it to him as json, so that he can show it. The data is very simple, but there is a problem in the processing. The file involves the processing of Chinese, and the json format is ASCII code after every processing, which cannot be used at all. The code is as follows:


# -*- coding: utf-8 -*-
import json
import codecs

f = codecs.open('data.txt', 'r', 'utf-8')
content = json.load(f)
print content[0]['id']
jsdata = json.dumps(content, sort_keys=True, indent=4)
f.close()


j = codecs.open('test.json', 'w')
j.write(jsdata)
j.close()

After checking 1 on the Internet, the modified code is as follows:


# -*- coding: utf-8 -*-
import json
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

f = open('data.txt', 'r')
content = json.load(f)
print content[0]['id']
#  Joining together json Data, transcode is not ascii coding 
jsdata = json.dumps(content, sort_keys=True, indent=4, ensure_ascii=False)
f.close()


j = open('test.json', 'w')
j.write(jsdata)
j.close()

Related articles: