Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count items in JSON data

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.

like image 249
mierzej Avatar asked Dec 05 '14 12:12

mierzej


People also ask

Can you do calculations in JSON?

No, it isn't possible to do math or any kind of expression in JSON as JSON is just a data structure format, and not a programming language.

How do you access a JSON array in Python?

You need to convert the string of a json object to python dict before you can access it. Show activity on this post. Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).


2 Answers

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.

like image 88
pnv Avatar answered Oct 02 '22 16:10

pnv


You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run']) 
like image 36
Muad'Dib Avatar answered Oct 02 '22 16:10

Muad'Dib