I've seen some similar questions but all those answers did not work for me unforunately.
I have a structure like this:
[
{"device": {
"key1": "value",
"list_key": [
{
"key1": "value",
"key2": "value",
"key3": "value",
"key4": "value",
}
{
"key1": "value",
"key2": "value",
"key3": "value",
"key4": "value",
}
],
"key2": "value",
"key3": "value",
}
},
{"device": {
"key1": "value",
"list_key": [
{
"key1": "value",
"key2": "value",
"key3": "value",
"key4": "value",
}
],
"key2": "value",
"key3": "value",
}
},
]
I want to create a csv out of this. I have the following issues:
- The Json is nested
- the list_key can contain multiple nested jsons, it can be 0 but 6 as well, we dont know.
What is the best approach? I tried to use pandas json_normalize() but that did not really gave me the right format
Also I used this flattening function;
def flatten_json(y):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out
Expected output: Each line 1 device like this:
key1,listkey.key11_0,listkey.key12_0,listkey.key13_0,listkey.key14_0,listkey.key11_1,listkey.key12_1,listkey.key13_1,listkey.key14_1, key2, key3