Json data is given below, I have to fetch the coords in the given data and print the list of it as:
Solution: [[2, 3], [4, 1], [8, 4], [3, 2]]
data = '{"foo": {"type": "geo", "coords": [2, 3], "children": [{"type": "geo", "coords": [4, 1], "children": [{"type": "bar", "children": [{"type": "geo", "coords": [8, 4]}]}, {"type": "geo", "coords": [3, 2]}]}]}}'
I have come up with a solution but that has indexing with it. I want some generic solution that works in every case of it, no matter what is the structure of dict. Is it possible? I yes then How?
My solution for this is:
def fun(data):
coords_list = list()
data = json.loads(data)
for k in data:
if data[k].get('coords') is not None:
coords_list.append(data[k]['coords'])
if data[k].get('children') is not None:
if isinstance(data[k].get('children'), list):
coords = data[k].get('children')[0].get('coords')
coords_list.append(coords)
if isinstance(data[k].get('children')[0].get('children'), list):
coords = data[k].get('children')[0].get('children')[0].get('children')[0].get('coords')
coords_list.append(coords)
coords = data[k].get('children')[0].get('children')[1].get('coords')
coords_list.append(coords)
return coords_list