I tried searching for similar questions but non of the ones I found do quite what I need.
I am trying to build a generic function that can take the 2 arguments:
- The object structure
- A list of (nested) paths
and convert all of the given paths to a list of flat dictionaries, suitable for outputting in CSV format.
So for example if I have a structure such as:
structure = {
"configs": [
{
"name": "config_name",
"id": 1,
"parameters": [
{
"name": "param name",
"description": "my description",
"type": "mytype",
},
{
"name": "test",
"description": "description 2",
"type": "myothertype",
"somedata": [
'data',
'data2'
]
}
]
},
{
"name": "config_name2",
"id": 2,
"parameters": [
{
"name": "param name",
"description": "my description",
"type": "mytype2",
"somedata": [
'data',
'data2'
]
},
{
"name": "test",
"description": "description 2",
"type": "myothertype2",
}
]
}
]
}
And pass the following list of paths:
paths = [
'configs.name', # notice the list structure is omitted (i.e it should be 'configs.XXX.name' where XXX is the elem id). This means I want the name entry of every dict that is in the list of configs
'configs.0.id', # similar to the above but this time I want the ID only from the first config
'configs.parameters.type' # I want the type entry of every parameter of every config
]
From this, the function should generate a list of flat dictionaries. Each entry in the list corresponds to a single row of the CSV. Each flat dictionary contains all of the selected paths.
So for example in this case I should see:
result = [
{"configs.name": "config_name", "configs.0.id": 1, "configs.parameters.type": "mytype"},
{"configs.name": "config_name", "configs.0.id": 1, "configs.parameters.type": "myothertype"},
{"configs.name": "config_name2", "configs.parameters.type": "mytype2"},
{"configs.name": "config_name2", "configs.parameters.type": "myothertype2"}
]
It needs to be able to do this for any structure passed, that contains nested dicts and lists.