Python json.dumps () Chinese garbled problem

Source: Internet
Author: User

Python outputs a string of Chinese characters that can be displayed correctly on the console (using UTF-8 encoding on the console) through print, but after writing to the file, the Chinese characters are printed in ASCII encoding. The English character can display readable characters normally.

Cause: Json.dumps The ASCII encoding that is used by default when serializing, want to output true Chinese need to specify ensure_ascii=false: more in-depth analysis, is to dJSON object is not purely Unicode implementation, Instead, it contains mixed Unicode encodings and strings that have been encoded with utf-8.

The possible ways are as follows:

1 ImportOS2 ImportOs.path3 Importio4 ImportSYS5 ImportJSON6 7Contentbypage = {}8contentbypage['Document'] =ShortName9contentbypage['content'] =textTencontentbypage['pagenumber'] =pagenumber OneJsonfile = Io.open (shortname+"--"+str (pagenumber) +". JSON",'W', encoding='UTF8') AJsonfile.write (Json.dumps (Contentbypage, Ensure_ascii=false). Decode ('UTF8')) - Jsonfile.flush () -Jsonfile.close ()

Python json.dumps () Chinese garbled problem

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.