i'm trying to parse my data from json. I have a function that loads all data... Data are like this:
devices_infos = get_devices()
{
"page" : 0,
"size" : 20,
"totalCount" : 2,
"data" : [ {
"namespace" : "android",
"id" : "0000001111111",
"creationTs" : 1516216756819,
"name" : "Eric's phone",
"description" : "This device was auto registered by [mqtt] ",
"tags" : [ ],
"properties" : { },
"lastUpdateTs" : 1518610495832,
"connected" : false,
"path" : [ ],
"metadata" : {
"api_key_id" : "XXX000XXX000XXX",
"connection_start_time" : "2018-02-14T12:14:04.778Z",
"mqtt_version" : 4,
"mqtt_username" : "json+device",
"mqtt_timeout" : 20,
"remote_addr" : "00.00.00.00/PORT"
},
"groupId" : "root",
"groupPath" : "/"
}, {
"namespace" : "sensor",
"id" : "temp001",
"creationTs" : 1520415684605,
"name" : "mySensor001",
"description" : "moisture sensor",
"tags" : [ "france", "lyon" ],
"properties" : {
"manufacturer" : "miel",
"model" : "MoistureSensorV3"
},
"lastUpdateTs" : 1520415684605,
"connected" : false,
"path" : [ ],
"groupId" : "root",
"groupPath" : "/"
} ]
I would like to extract the name of the devices via a for loop like this:
if devices_infos is not None:
print('Devices are: ')
for each in devices_infos['data'][0]['name']:
print (each)
else:
print("[!] Request failed")
This only print me the first device, ie Eric's phone , i would like to have too mySensor001.
['data']['name']does not work because it applies to the list itself not the list elements. The['blabla']selector is for object key/value pairs like{"a": 42}and does not apply to lists, for lists the[ ]operator is directly accessing an index (first element, second element, ...). Example by Pradam is a list comprehension which another way to access elements in python.