+4 votes
15.6k views
in Programming by

I have a JSON like below :

 

var source=[{'k':'01'} ,
{'k':'02','children':[{'k':'05'},{'k':'06', 'children':[{'k':'ABC'},{'K':'PQR'}]},{'k':'07'}]},
{'k':'03'}];


Here I want to get child like k=02 which would return its all children or grand children if available. Any good solution to get children and grandchildren of that node???

5 Answers

0 votes
by
You can loop through the value that you get when running command 'source[1].children'. You will get all the children object. Which can be further looped to get grandchildren object
0 votes
by
if you can use jQuery there is the $.parseJSON() function that will transform your json into an object which you can process easier.
0 votes
by
It seems you are want to read hierarchical data from a JSON string. First you need to parse the data into a JSON object. Then if the number of nesting level is fixed then you should go for iterative method of fetching the data for each child. If the level is unknown then it is the case of recursive function call. Iteration method is always TIME and SPACE effective way of parsing the fixed length levels. But recursive one is a flexible and good for traversing unknown level of childs.
0 votes
by
I hope it'll help you
test_1.php ---------------------------
<?php
$data = array(
    'k' => '01',
    'k' => '01',
    'child' => array(),
);

for ($index = 0; $index < 20; $index++) {
    $data['child'][] = "ch - $index";
}

echo json_encode($data);
?>

test.php -------------------------------
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="resources/js/jquery-1.8.1.min.js"></script>
        <script>
            $(function() {
                $.ajax({
                    url: 'test_1.php',
                    type: 'get',
                    success: function(data){
                        //                        ////alert(data);
                        $('#main').empty().append(data+"<br/>");
                        obj = JSON.parse(data);
                        $('#main').append(obj.child+"<br/>");
                        for(i = 0; i < obj.child.length; i++) {
                            $('#main').append(obj.child[i]+"<br/>");
                        }

                    },
                    error: function(){
                    }
                });
                return false;
            });
        </script>
    </head>
    <body>
        <div id="main" >

        </div>

    </body>
</html>

to try this script (php) deploy it in your php server then >> http://localhost/test.php

good luck
+1 vote
by (160 points)

i know it's too late but it was very easy Using recursive Function as you object seems to be the same on all other levels 
Just reformatted the Object for clearer view 
var source = [
    {
        "k": "01"
    },
    {
        "k": "02",
        "children": [
            {
                "k": "05"
            },
            {
                "k": "06",
                "children": [
                    {
                        "k": "ABC"
                    },
                    {
                        "K": "PQR"
                    }
                ]
            },
            {
                "k": "07"
            }
        ]
    },
    {
        "k": "03"
    }
]
function getChilds(source){ 

       source.forEach(function(x,y){ 

           console.log(x.k); 

          if( x.children != undefined){ 

                    getChilds(x.children); 

           } 

        })

}

 

and Finlay call getChilds(source); it will recursively Traverse the object and print the value of any node it visits 
it's like traversing tree , reading about tree data structure will definitely help you understand better 

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated