In current data "children"
key will be fix. If there is any child data available then there then it must in list of dictionary format.
If there is no any children available then it no "children"
key is available in dictionary.
I don't want to use the loop to bifurcate this data. I want the same consistent sequence data. Please note there will any number of hierarchy available.
I want all this data in list of dictionary format like given requirement data example.
Current data.
{
"id": 2,
"parent_id": 1,
"name": "0",
"is_active": true,
"position": 1,
"level": 1,
"children": [
{
"id": 8,
"parent_id": 1,
"name": "01",
"is_active": false,
"position": 1,
"level": 2,
"children": [
"id": 9,
"parent_id": 1,
"name": "010",
"is_active": false,
"position": 1,
"level": 2,
"children": [
<'Here N number of hirerchy availabe'>
]
]
},
],
"id": 3,
"parent_id": 1,
"name": "1",
"is_active": true,
"position": 1,
"level": 1,
"children": [
{
"id": 5,
"parent_id": 1,
"name": "03",
"is_active": false,
"position": 1,
"level": 2,
"children": [
"id": 6,
"parent_id": 1,
"name": "030",
"is_active": false,
"position": 1,
"level": 2,
"children": [
<'Here N number of hirerchy availabe'>
]
]
},
]
}
Requirement.
[{
"id": 2,
"parent_id": 1,
"name": "0",
"is_active": true,
"position": 1,
"level": 1,
},
{
"id": 3,
"parent_id": 1,
"name": "01",
"is_active": false,
"position": 1,
"level": 2,
},
{
"id": 3,
"parent_id": 1,
"name": "01",
"is_active": false,
"position": 1,
"level": 2,
},{
<N Number of dictionary data with consistant sequence>
}]
The suitable answer will definitely acceptable.
You can flatten the given nested data structure with a recursive function like this:
def flatten(data):
if isinstance(data, dict):
return [data, *flatten(data.pop('children', ()))]
return [subrecord for record in data for subrecord in flatten(record)]
Demo: https://repl.it/@blhsing/BlankHatefulResources
I have found the solution to my question. Below code is working for me.
if isinstance(categories, dict):
values = {
'name': categories.get('name'),
'parent_id': categories.get('parent_id'),
'magento_id': categories.get('id'),
'instance_id': instance.id
}
self.category_list.append(values)
self._analyse_response_data(categories.get('children_data'), instance)
if isinstance(categories, list):
for category in categories:
values = {
'name': category.get('name'),
'parent_id': category.get('parent_id'),
'magento_id': category.get('id'),
'instance_id': instance.id
}
self.category_list.append(values)
self._analyse_response_data(category.get('children_data'), instance)
return self.category_list
I have used recursion to fulfil my requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With