I am looking into ways on how I can flatten the nested list in a dict which is nested in a list using python.
The example as below:
[
{
"id": 8,
"category": {
"id": 0,
"name": "lion"
},
"name": "Leon",
"photoUrls": [
"123",
"444",
],
"tags": [
{
"id": 1,
"name": "TagLion"
},
{
"id": 2,
"name": "KingOfTheJungle"
}
],
},
{
"id": 83,
"category": {
"id": 0,
"name": "dog UPDATED"
},
"name": "Buff",
"photoUrls": [
"333",
],
"tags": [
{
"id": 1,
"name": "TagNumber1UPDATED"
},
{
"id": 2,
"name": "DogWithStickUPDATED"
}
],
}
]
From the example above, which is a return from API, I would like to write the output to csv. But the catch here is on the "tags" where it is a nested list. I would like the above result to be flatten to csv format as below:
id | category | name | photoUrls | tags
8 |{'id': 0, 'name': 'dog UPDATED'}| Leon | 123 | {'id': 1, "name": "TagLion"}
83 |{'id': 0, 'name': 'dog UPDATED'}| Buff | 333 | {"id": 1,"name": "TagNumber1UPDATED"}
83 |{'id': 0, 'name': 'dog UPDATED'}| Buff | 333 | {"id": 2,"name": "name": "DogWithStickUPDATED"}
How can I do this using python? Would like this to be set as a configuration and when loading to csv, python will look for this config to flatten the array "tags"
EDIT: would like to flatten the photourls column as well which is a array. result as below , by piping it instead of splitting it.
id | category | name | photoUrls | tags
8 |{'id': 0, 'name': 'dog UPDATED'}| Leon | 123 |444 | {'id': 1, "name": "TagLion"}
8 |{'id': 0, 'name': 'dog UPDATED'}| Leon | 123 | {'id': 1, "name": "TagLion"}
8 |{'id': 0, 'name': 'dog UPDATED'}| Leon | 123 | {'id': 2, "name": "KingOfTheJungle"}
83 |{'id': 0, 'name': 'dog UPDATED'}| Buff | 333 | {"id": 1,"name": "TagNumber1UPDATED"}
83 |{'id': 0, 'name': 'dog UPDATED'}| Buff | 333 | {"id": 2,"name": "name": "DogWithStickUPDATED"}