Maison  >  Article  >  développement back-end  >  在python中转换JSON 字符串

在python中转换JSON 字符串

巴扎黑
巴扎黑original
2016-12-09 10:26:271698parcourir

我们在开发一个Web服务时,可能会使用基于JSON的Web服务协议。如果你使用Python语言来开发的话,它的扩展模块是能直接处理JSON格式的消息。例如,在Python2.6中引入的Python的JSON模块提供了默认的JSON编码器和解码器,当然你可以安装和使用其他的JSON编码器/解码器。

下面的代码片段是在Python中解析JSON的例子

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"

下面是例子打印的结果

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


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:python 正文内容提取Article suivant:Java调用Python