Home  >  Article  >  Backend Development  >  Convert JSON string in python

Convert JSON string in python

巴扎黑
巴扎黑Original
2016-12-09 10:26:271629browse

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"

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


Statement:
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