Solution to reading and writing json Chinese ASCII garbled characters

Source: Internet
Author: User
The following small series will bring you a solution to the problem of reading and writing json Chinese ASCII garbled characters. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the small Editor. today we want to help the front end write a small background, that is, read the data and convert it into json for him to show. The data is very simple, but there is a problem during processing. the file involves Chinese processing, and the json format written after each processing is ASCII code, which is totally useless. The code is as follows:

# -*- coding: utf-8 -*-import jsonimport codecsf = 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 it online. the modified code is as follows:

#-*-Coding: UTF-8-*-import jsonimport sysreload (sys) sys. setdefaultencoding ("UTF-8") f = open('data.txt ', 'r') content = json. load (f) print content [0] ['id'] # concatenate json data and transcode it to non-ascii encoded 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 reading and writing json Chinese ASCII garbled characters is all the content shared by Xiaobian. I hope to give you a reference and support for PHP.

For more information about how to solve the Chinese ASCII garbled characters in json reading and writing, see The PHP Chinese website!

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.