A solution to read and write JSON Chinese ASCII garbled problem _python

Source: Internet
Author: User

Today to help the front to write a small background, is to read the data and then turn to JSON to give him, let him show. The data is very simple, but when processing encountered a problem, the file involved in the Chinese processing, each processing the written JSON format is ASCII code, completely no way to use. 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 ()

Check the Internet, the revised 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 ']
# stitching JSON data, transcoding to non-ASCII encoding
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 read and write JSON Chinese ASCII garbled problem solution is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.