简体   繁体   English

如何在python中解析json字符串?

[英]How to parse json string in python?

Below code is running fine. 下面的代码运行正常。

 import json
 json_data = '{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"}'
        json_parsed = json.loads(json_data)
        print(json_parsed['Detail'])
        print(json_parsed['Amount'])
        print(json_parsed['Validity'])

How to parse below json string? 如何解析JSON字符串以下? and How to display all values also? 以及如何也显示所有值?

json_data = '[{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"},{"Detail":" Rs. 1900 Topup Rs.1690.99 Talktime","Amount":"1900","Validity":"Unlimited"}]'

Please help me. 请帮我。

This json string is an array of objects, as opposed to a single object. 此json字符串是对象的数组,而不是单个对象。

You'd parse it the same way with the json module, however instead of getting a single dictionary you would get a list of dictionaries. 您可以使用json模块以相同的方式解析它,但是,除了获取单个字典之外,您还将获得字典列表。

you'd be able to display as so: 您将可以这样显示:

import json

json_data = '[{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"},{"Detail":" Rs. 1900 Topup Rs.1690.99 Talktime","Amount":"1900","Validity":"Unlimited"}]'

# convert to python data structure
d_list = json.loads(json_data)

# loop through the list
for d in d_list:
    # use get for safety
    print d.get('Detail')
    print d.get('Amount')

Regardless of the parsing language, python, javascript, php and so on, any json string or subset of a json string that has objects wrapped in [brackets] will be an array, and will need to be handled in a similar (language specific) fashion. 无论使用哪种解析语言,python,javascript,php等,任何将对象包装在[花括号]中的json字符串或json字符串的子集都将是一个数组,并且需要以类似的方式处理(特定于语言)时尚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM