Convert JSON string in python

巴扎黑
Release: 2016-12-09 10:26:27
Original
1734 people have browsed it

When we develop a Web service, we may use a JSON-based Web service protocol. If you use the Python language to develop, its extension module can directly handle messages in JSON format. For example, Python's JSON module introduced in Python 2.6 provides a default JSON encoder and decoder, but of course you can install and use other JSON encoders/decoders.

The code snippet below is an example of parsing JSON in Python

import json
 
json_input = '{ "one": 1, "two": { "list": [ {"item":"A"},{"item":"B"} ] } }'
 
try:
    decoded = json.loads(json_input)
 
    # pretty printing of json-formatted string
    print json.dumps(decoded, sort_keys=True, indent=4)
 
    print "JSON parsing example: ", decoded['one']
    print "Complex JSON parsing example: ", decoded['two']['list'][1]['item']
 
except (ValueError, KeyError, TypeError):
    print "JSON format error"
Copy after login

The following is the result printed by the example

{
    "one": 1,
    "two": {
        "list": [
            {
                "item": "A"
            },
            {
                "item": "B"
            }
        ]
    }
}
JSON parsing example:  1
Complex JSON parsing example:  B
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!