如何从JSON字符串中提取特定字段

2024-05-21 00:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下JSON字符串,我想获得doc_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']['buckets']['doc_count'],但没用。如何搜索这个JSON文件的层次结构?你知道吗


Tags: totextfromjsonobjstringdocas
2条回答

因为'buckets'键包含元素数组。你需要

obj['aggregations']['range']['buckets'][0]['doc_count']

您忽略了"buckets"键包含一个列表的事实。您需要:

obj['aggregations']['range']['buckets'][0]['doc_count']

注意选择bucket键之后的[0]。你知道吗

相关问题 更多 >