0

I have the following JSON string and I want to obtain 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

I tried obj['aggregations']['range']['buckets']['doc_count'], but it does not work. How can I search through the hierarchy of this JSON file?

Dinosaurius
  • 8,306
  • 19
  • 64
  • 113

2 Answers2

1

You're missing the fact that the "buckets" key contains a list. You need:

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

Note the [0] after selecting the buckets key.

John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
1

Because 'buckets' key contains array of element. You needs

obj['aggregations']['range']['buckets'][0]['doc_count']
kvorobiev
  • 5,012
  • 4
  • 29
  • 35