I have a data structure I have read from a file which looks like below –
data = {"test":['[{"Day":"Monday","Device":"Android","Data":[1, 2, 3]}, {"Day":"Tuesday","Device":"Iphone","Data":[10, 20, 30]}]']}
I am trying to access the elements of the structure like below, peeling off one by one –
value = data["test"]
print(value)
#['[{"Day":"Monday","Device":"Android","Data":[1, 2, 3]}, {"Day":"Tuesday","Device":"Iphone","Data":[10, 20, 30]}]']
value1 = value[0]
print(value1)
#[{"Day":"Monday","Device":"Android","Data":[1, 2, 3]}, {"Day":"Tuesday","Device":"Iphone","Data":[10, 20, 30]}]
print(value1[0])
#I get only [ as if it is a string
Does the incoming structure has some problems, or am I accessing the wrong way.
Here is the link to reproduce – https://godbolt.org/
>Solution :
You can use the built-in JSON parser to convert this to a dictionary like so:
import json
for item in json.loads(data['test'][0]):
print(item, type(item))
# >>> {'Day': 'Monday', 'Device': 'Android', 'Data': [1, 2, 3]} <class 'dict'>
# >>> {'Day': 'Tuesday', 'Device': 'Iphone', 'Data': [10, 20, 30]} <class 'dict'>
Note: printing type(item) is just to demonstrate that they’re being converted to dict appropriately