Reputation: 87
I'm trying to iterate through this json array :
[{
"date": "2018-02-21T12:53:00",
"name": "System date",
"ID_BBData": "none",
"TOKEN_BBData": "none",
"rawValue": 540916682
},
{
"date": "2018-02-21T12:53:00",
"name": "Temperature sensor 1",
"ID_BBData": "none",
"TOKEN_BBData": "none",
"rawValue": 11
},
{
"date": "2018-02-21T12:53:00",
"name": "Value week",
"ID_BBData": "none",
"TOKEN_BBData": "none",
"rawValue": 1810
}]
With this loop :
# print the keys and values
for key in jsonObject:
value = jsonObject[key]
print("The key and value are ({}) = ({})".format(key, value))
Where jsonObject is the json above. The problem is that the json is enclosed by [] but there isn't any name to this array.
Any clue to iterate through this one ?
Thanks a lot !
Upvotes: 3
Views: 4864
Reputation: 26708
First, convert the JSON array, then loop over it to get values as dictionaries.
data = json.loads(array)
for event in data:
...
Upvotes: 1
Reputation: 7716
At first, you should understand that your object is a list of dictionaries. You can check this easily, if you put the data into a variable, say lst, and then check the types:
>>> lst
[{'date': '2018-02-21T12:53:00', 'name': 'Temperature sensor 1', 'ID_BBData': 'none', 'TOKEN_BBData': 'none', 'rawValue': 11}, {'date': '2018-02-21T12:53:00', 'name': 'Value week', 'ID_BBData': 'none', 'TOKEN_BBData': 'none', 'rawValue': 1810}]
>>> type(lst) # the type of the whole datastructure
<class 'list'>
>>> type(lst[0]) # the type of the first element of the list
<class 'dict'>
If you understand, that you have such a structure, you can begin to think about looping through the items of the list, of which each is a dictionary:
>>> for lst_item in lst:
... for key, value in lst_item.items(): # this is python3 specific
... print('key: {} value: {}'.format(key, value))
...
key: date value: 2018-02-21T12:53:00
key: name value: Temperature sensor 1
key: ID_BBData value: none
key: TOKEN_BBData value: none
key: rawValue value: 11
key: date value: 2018-02-21T12:53:00
key: name value: Value week
key: ID_BBData value: none
key: TOKEN_BBData value: none
key: rawValue value: 1810
If you want to iterate a dictionary in python2, use
for key, value in lst_item.iteritems():
instead.
Upvotes: 2
Reputation: 407
If you want to iterate over all list elements (as mentioned in comments, it's a list not a json object):
for line in jsonObject:
for key, value in line.items():
print("The key and value are ({}) = ({})".format(key, value))
Upvotes: 1