Chinese in python processing json data-Python tutorial

Source: Internet
Author: User
This article mainly introduces the Chinese problem of python processing json data. if you need it, you can refer to the python module that handles python. you can directly import json when using it. You can use the loads method to convert a json string to a python object. the corresponding relationship is as follows:
JSON Python
Object dict
Array list
String unicode
Number (int) int, long
Number (real) float
True
False False
Null None

However, when using the json module, you need to pay attention to the processing of Chinese, loads method if the input string encoding is not a UTF-8, you need to use encoding to specify the character encoding

The code is as follows:


Import json
Import base64
F = open ("./result_diff.txt ")
For l in f:
Try:
Fp = l [l. find ("? Fp ") + 1:]
Http = fp. find ("HTTP /")
Fp = fp [3: Http-1]
Fp = fp. decode ("gbk"). encode ("UTF-8 ")
Str1 = json. loads (fp, encoding = "UTF-8 ")
Print str1
Except t Exception, e:
Print str (e)

When fp contains Chinese characters and gbk encoding, we need to specify the encoding when converting the current line encoding to utf8 and then decoding using json.
Or

The code is as follows:


Fp = fp. decode ("gbk ")


Directly convert to gbk encoding, you do not need to specify the json encoding type, that is, you do not need to use the encoding parameter
Related Article

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.