Recursive function to create hierarchical JSON object?

后端 未结 5 1972
庸人自扰
庸人自扰 2021-02-08 19:08

I\'m just not a good enough computer scientist to figure this out by myself :(

I have an API that returns JSON responses that look like this:

// call to         


        
5条回答
  •  无人及你
    2021-02-08 19:25

    Disclaimer : I have no idea what json is about, so you may have to sort out how to write it correctly in your language :p. If the pseudo-code in my example is too pseudo, feel free to ask more details.

    You need to return something somewhere. If you never return something in your recursive call, you can't get the reference to your new objects and store it in the objects you have where you called the recursion.

    def getChildNodes (node) returns [array of childNodes]
        data = getData(fromServer(forThisNode))
        new childNodes array
        for child in data :
            new temp_obj
            temp_obj.stores(child.interestingStuff)
            for grandchild in getChildNodes(child) :
                temp_obj.arrayOfchildren.append(grandchild) 
            array.append(temp_obj)
        return array
    

    Alternatively, you can use an iterator instead of a return, if your language supports it.

提交回复
热议问题