Home  >  Article  >  Backend Development  >  Solution to the problem of reading and writing Chinese ASCII garbled json

Solution to the problem of reading and writing Chinese ASCII garbled json

高洛峰
高洛峰Original
2017-02-22 11:02:461641browse

Today I am going to write a small backend for the front end, which is to read the data and then convert it into json and send it to him for display. The data is very simple, but we encountered a problem during processing. The file involves Chinese processing. The json format written after each processing is ASCII code, which is completely unusable. 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()

I checked online and 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']
# 拼接json数据,转码为非ascii编码
jsdata = json.dumps(content, sort_keys=True, indent=4, ensure_ascii=False)
f.close()


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

The above solution to the problem of reading and writing json Chinese ASCII garbled characters is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more related articles on solutions to the problem of reading and writing json Chinese ASCII garbled characters, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn