Python 如何从JSON字符串中提取特定字段
我有以下JSON字符串,我想获得Python 如何从JSON字符串中提取特定字段,python,json,python-2.7,Python,Json,Python 2.7,我有以下JSON字符串,我想获得doc\u count: import json text = '''{ "took": 1, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 11, "max_score": 0, "hits": [] }, "aggregations": {
doc\u count
:
import json
text = '''{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 11,
"max_score": 0,
"hits": []
},
"aggregations": {
"range": {
"buckets": [
{
"key": "2017-02-17T15:00:00.000Z-2017-02-17T16:00:00.000Z",
"from": 1487343600000,
"from_as_string": "2017-02-17T15:00:00.000Z",
"to": 1487347200000,
"to_as_string": "2017-02-17T16:00:00.000Z",
"doc_count": 2
}
]
}
}
}'''
obj = json.loads(text)
obj
我尝试了
obj['aggregations']['range']['bucket']['doc\u count']
,但它不起作用。如何搜索此JSON文件的层次结构?您缺少一个事实,即“bucket”
键包含一个列表。你需要:
obj['aggregations']['range']['buckets'][0]['doc_count']
obj['aggregations']['range']['buckets'][0]['doc_count']
请注意选择bucket键后的
[0]
。您缺少一个事实,即“bucket”
键包含一个列表。你需要:
obj['aggregations']['range']['buckets'][0]['doc_count']
obj['aggregations']['range']['buckets'][0]['doc_count']
请注意选择bucket键后的
[0]
。因为'bucket'
键包含元素数组。你需要
因为
“bucket”
键包含元素数组。你需要