parsing json fields in python

故事扮演 提交于 2019-12-03 13:01:59

问题


Is there a good tutorial on parsing json attributes in python? I would like to be able to parse the true value for "ok" field. As well as the index named "client_ind_1". I don't understand the python document coverage on this topic. If someone could explain or point me to a better resource, it would be awesome.

My json string looks like the below:

{
    "ok": true,
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "indices": {
        "client_ind_2": {
            "index": {
                "primary_size": "2.5mb",
                "primary_size_in_bytes": 2710326,
                "size": "2.5mb",
                "size_in_bytes": 2710326
            }
        }
    }
}

Thank you in advance.


回答1:


import json

a =  """{
    "ok": true,
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "indices": {
        "client_ind_2": {
            "index": {
                "primary_size": "2.5mb",
                "primary_size_in_bytes": 2710326,
                "size": "2.5mb",
                "size_in_bytes": 2710326
            }
        }
    }
}"""

b = json.loads(a)

print(b['ok'])
print(b['indices']['client_ind_2']['index'])

This will take json as python dictionary and will print 'ok' and index value you want:

True
{u'primary_size': u'2.5mb', u'primary_size_in_bytes': 2710326, u'size_in_bytes': 2710326, u'size': u'2.5mb'}



回答2:


import json
dct = json.loads(my_json_str)
is_ok = dct['ok']
client_index = dct['indices']['client_ind_2']['index']


来源:https://stackoverflow.com/questions/19573747/parsing-json-fields-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!