How to count items in JSON data

mierzej picture mierzej · Dec 5, 2014 · Viewed 143.9k times · Source

How I can get the number of elements in node of JSON data?

JSON:

{
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find":true
    }
  ]
}

I need to get the number of elements from node data['result'][0]['run']. It should be 3, but I can't find how to do it in Python.

Answer

pnv picture pnv · Dec 8, 2014
import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.