I want to create a list of dictionaries from a json value in python. The json data is
{
"data": [
{
"date": "2017-07-28_15-54-10",
"name": "name1",
"state": "true"
},
{
"date": "2017-07-29_15-54-10",
"name": "name2",
"state": "true"
}
]
}
I want to put this data in a Array of dicts(name1,name2,name3) containing array of dicts(the "data" part of json), something like
[
{
"name1": [
{
"date": "2017-07-28_15-54-10"
},
{
"state": "true"
}
]
},
{
"name2": [
{
"date": "2017-07-28_15-54-10"
},
{
"state": "true"
}
]
}
]
I got all the data and my code is
for jn in data:
name = jn.get("name")
my_dict = {}
my_dict1 = {}
my_list = []
my_dict["date"] = jn.get("date")
my_dict1["state"] = jn.get("state")
my_list.append(my_dict) # dict for date
my_list.append(my_dict1) # dict for state
my_name_dict = {}
my_name_dict[name] = my_list # add the small dicts to the "name" dict
my_final_array.append(my_name_dict)
print(my_final_array)
I am able to get this output
{
"name1": [
{
"date": "2017-07-28_15-54-10"
},
{
"state": "true"
}
]
},
{
"name2": [
{
"date": "2017-07-28_15-54-10"
},
{
"state": "true"
}
]
}
I am struggling with adding these dicts to a list/array. When i print the value of my_final_array i just get the last line of the dict and not all the lines in the list.
My code is also a little bit messy, is there any other way to do this?