-1

I have a nested JSON object having the following structure. I would like to retrieve all nested level "concept" elements under the main level "details". I'm having trouble in accessing those inner layers of json recursively and getting it's corresponding values..

d = {"canonical": None, 
     "concept": "_MAIN", 
     "correct_string": "xxx", 
     "definition": "",
     "details": [{
                   "details": [{
                        "concept": "_A",
                            "details": [{
                                "concept": "_B",
                                    "details": [{
                                        "concept": "_C",
                                            "details": [{
                                                "concept": "_D", ....

Expected output:

details_concepts = ['_A', '_B', 'C', 'D']

Any help would be greatly appreciated.

nikinlpds
  • 411
  • 3
  • 8
  • 1
    Possible duplicate of [Python Accessing Nested JSON Data](https://stackoverflow.com/questions/23306653/python-accessing-nested-json-data) – Mike Scotty Jun 11 '18 at 10:01

2 Answers2

0

You can easily do this by using Recursion, check the following code

d={"canonical": None,
     "concept": "_MAIN", 
     "correct_string": "xxx", 
     "definition": "",
     "details": [{
                   "details": [{
                        "concept": "_A",
                            "details": [{
                                "concept": "_B"
                    }]
                }]
        }]
  }
details_concepts=[]
def parse_json(det):
    if 'concept' in det[0]:
        details_concepts.append(det[0]['concept'])
    if 'details' in det[0]:
        return parse_json(det[0]['details'])
    else:
        return details_concepts
print(parse_json(d['details']))

I considered your inner details list has only single dictionary, that's the reason I kept det[0] directly.

Murali
  • 364
  • 2
  • 11
0

Using recursion, you can check for base case using key concept and return values on passing base condition as follows:

def get_data_by_key(data):
    if 'concept' in data:
        yield data['concept']
    details = data.get('details')
    if details:
        if isinstance(details, list):
            for inner_item in details:
                for i in get_data_by_key(inner_item):
                    yield i


data = {'canonical': None, 'concept': '_MAIN', 'correct_string': 'xxx', 'definition': '',
        'details': [{'concept': '_A', 'details': [{'concept': '_B', 'details': [{'concept': '_C'}]}]}]}
concepts = list(get_data_by_key(data['details'][0]))
print(concepts)

output : ['_A', '_B', '_C']
Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36