Example of parsing JSON in Python and customizing encoding at the same time

Source: Internet
Author: User
This article describes how to parse JSON in Python and perform custom encoding at the same time. For more information about how to deserialize the file content or strings, see deserialize, due to the encoding problem of the original content, the deserialized content may need to be encoded (for example, converting unicode objects to str ).

In Python, one way is to use json. load or json. loads deserialization to obtain the dict object, and then encode the dict object.

However, in json. load and json. loads, the optional parameter object_hook exists. By using this parameter, you can directly process the deserialized dict and use the new dict to replace the original dict.

Usage:

The code is as follows:


D = json. loads (json_str, object_hook = _ decode_dict)

See _ decode_dict and _ decode_list used in Shadowsocks:

The code is as follows:


Def _ decode_list (data ):
Rv = []
For item in data:
If isinstance (item, unicode ):
Item = item. encode ('utf-8 ')
Elif isinstance (item, list ):
Item = _ decode_list (item)
Elif isinstance (item, dict ):
Item = _ decode_dict (item)
Rv. append (item)
Return rv

Def _ decode_dict (data ):
Rv = {}
For key, value in data. iteritems ():
If isinstance (key, unicode ):
Key = key. encode ('utf-8 ')
If isinstance (value, unicode ):
Value = value. encode ('utf-8 ')
Elif isinstance (value, list ):
Value = _ decode_list (value)
Elif isinstance (value, dict ):
Value = _ decode_dict (value)
Rv [key] = value
Return rv

Refer:
1. https://docs.python.org/2/library/json.html
2. https://github.com/clowwindy/shadowsocks/blob/master/shadowsocks/utils.py

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.