0

This is a follow up on this question. Question

Also this question is similar but does not solve my problem Question2

I am trying to parse a nested json to get Check how many children a specific location has, I am trying to check if "children:" = None and increment counter to check how many levels down i need to go in order to get the lowest child, or A more efficient solution would be:

I need to get all the child values into a list and keep going until "children:" = None.

The Json object can increase in the amount of children so we can have multiple level of children, Which can get messy if I want to nest the list and get the values, How could I do it dynamically?

{
    'locationId': 'location1',
    'name': 'Name',
    'type': 'Ward',
    'patientId': None,
    'children': [{
        'locationId': 'Child_location2',
        'name': 'Name',
        'type': 'Bed',
        'patientId': None,
        'children': [{
            'locationId': 'Child_Child_location3',
            'name': 'Name',
            'type': 'HospitalGroup',
            'patientId': None,
            'children': None
        }]
    }, {
        'locationId': 'location4',
        'name': 'Name',
        'type': 'Hospital',
        'patientId': None,
        'children': None
    }, {
        'locationId': 'location5',
        'name': 'Name',
        'type': 'Bed',
        'patientId': None,
        'children': None
    }, {
        'locationId': 'location6',
        'name': 'Name',
        'type': 'Bed',
        'patientId': None,
        'children': None
    }, {
        'locationId': 'location27',
        'name': 'Name',
        'type': 'Bed',
        'patientId': None,
        'children': None
    }]
}

I tried to do something like this

import requests
def Get_Child(URL, Name):
        headers = {
            'accept': 'text/plain',
        }

        response = requests.get(
            URL + Name,
            headers=headers)
        json_data = response.json()
        print (json_data)
        list = []
        for locationId in json_data['locationId']:
            list.append(locationId)
            for children in locationId['children']:
                list.append(children)

but that give me the following error,

for children in locationId['locationId']: TypeError: string indices must be integers
8
  • 1
    Your starting point should probably be using the parsed JSON, not the raw body. Commented Nov 21, 2018 at 14:41
  • you could use a recursive function Commented Nov 21, 2018 at 14:42
  • @jonrsharpe I have edited my question. Thanks for the comment Commented Nov 21, 2018 at 14:47
  • Your question is no longer internally consistent - access to json would be a NameError, and I doubt you'd see the same error as before if you fixed that. Commented Nov 21, 2018 at 14:51
  • @jonrsharpe Yes you are correct I am getting a diffrent error i Updated my question Commented Nov 21, 2018 at 15:01

2 Answers 2

1

Your code shows append, but you ask for a count. Here is a recursive way to get the number of children in this JSON if I am understanding you correctly:

def get_children(body, c=1):
    if not body.get('children'):
        c += 1
    elif isinstance(body.get('children'), list):
            c += 1
            for subchild in body.get('children'):
                c += 1
                get_children(subchild, c)
    return c

counts = get_children(your_json_blob)
print(counts)
>>> 7

Edit: I purposely did not use if/else because I don't know if you can have subchildren that are dict rather than list which would mean you would need extra conditions, but that's up to you if that ends up being the case.

Sign up to request clarification or add additional context in comments.

Comments

0

I found a solution fro my problem,

The following code will get all the children and append them to a list

class Children():
  def Get_All_Children(self,json_input, lookup_key):
      if isinstance(json_input, dict):
          for k, v in json_input.items():
              if k == lookup_key:
                  yield v
              else:
                  yield from self.Get_All_Children(v, lookup_key)
      elif isinstance(json_input, list):
          for item in json_input:
              yield from self.Get_All_Children(item, lookup_key)


for locations in self.Get_All_Children(self.json_data, 'locationId'):
    self.mylist.append(locations)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.