Python handles Chinese in json data

  • 2020-04-02 13:28:38
  • OfStack

Python comes with a python module to handle the use of direct import json can be. Using the loads method, the json string can be converted into a python object. The corresponding relationship is as follows:
JSON         Python
The object       dict
array       The list
The string       unicode
number     (int) int, long
number     Float (real)
True,         True,
false       False
null         None

However, when using the json module, it is important to pay attention to the handling of the Chinese language. The loads method needs to specify the character encoding with encoding if the encoding of the incoming string is not utf-8


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 Exception, e:
print str(e)

When fp contains Chinese and is GBK encoded, we need to specify the encoding when decoding with json after changing the current row encoding to utf8.
Or it


fp = fp.decode("gbk")

To convert directly to GBK encoding, you can do this without specifying the encoding type of json, which means you don't use the encoding parameter

PS: about json operation, here again for you to recommend a few more practical json online tools for your reference:

Online JSON code verification, verification, beautification, formatting tools:
(link: http://tools.jb51.net/code/json)

JSON online formatting tool:
(link: http://tools.jb51.net/code/jsonformat)

Online XML/JSON interconversion tool:
(link: http://tools.jb51.net/code/xmljson)

Json code online formatting/beautification/compression/editing/conversion tools:
(link: http://tools.jb51.net/code/jsoncodeformat)

Online json compression/escape tool:

(link: http://tools.jb51.net/code/json_yasuo_trans)

C language style /HTML/CSS/json code format beautification tool:
(link: http://tools.jb51.net/code/ccode_html_css_json)  


Related articles: