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

高洛峰
Release: 2017-02-22 11:02:46
Original
1695 people have browsed it

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template