Home > Mobile >  How to iterage with Json looking for determinate index?
How to iterage with Json looking for determinate index?

Time:10-06

To start, I have a JSON which contain arrays and dicts, this is a example of structure.

JSON {} 
 - nav []
   - 0 {title, view-list, ...}
    - subitems []
      - 0 {title, view-list, ...}

Thinking in that structured, inside array nav, I have dicts which contains datas as title and view-list two of exists importants content which need extract. but inside dicts there is anothers arrays with other dicts with theses importants values title, view-list.

JSON
navtree
     0
      id : 811566
      title : "Services"
      view-list : "2"
      subsections
        0
         id : 811568
         title : "inetd Services"
         view-list : "2.1"

navtree can has 10 positions, each position can has another 10 and so on. This would be a extensive nested for loop. How I would extract these values using a recursive way?

Json Data - https://pastebin.com/27JHunmn

CodePudding user response:

Recursion is what you would want.

Here is a complete example for your use case. Parsing the dictionary to one list of NavItem objects.

# Nav Item object - makes it easier to work with later on.
class NavItem():
    def __init__(self, title, view_level, **kwargs):
        self.title = title
        self.view_level = view_level

# parse nested Array of Dict Items to Array of NavItem
def parseNavItems(Items):
    parsedItems = []
    for Item in Items:
        for k in {'subsections_for_nav_tree', 'recommendations_for_nav_tree'}:
            if k in Item:
                parsedItems.extend(parseNavItems(Item[k]))
        parsedItems.append(NavItem(**Item))
    return parsedItems

You would call the function with allItems = parseNavItems(j['navtree']) - whatever your j is. You may extract the data with allItems[0].title by utilizing the NavItem class.

  • Related