I have a JSON input which can go to any number of levels.

I'm giving an input sample of

var d=getEntities( {"Categories": 
{
"Facets": 
    [
    {
    "count": 1,
    "entity": "Company",
    "Company": 
            [
            {

            "entity": "Ford Motor Co",

            "Ford_Motor_Co": 
                [
                    {
                    "count": 1,
                    "entity": "Ford"
                    }
                ]
            }
            ]
    },
        {
            "count": 4,
            "entity": "Country",
              "Country": [
                    {

                        "entity": "Germany",
                         "Germany": [
                                {
                                    "count": 1,
                                    "entity": "Germany"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                         "entity": "Italy",
                        "Italy": [
                                {
                                     "count": 1,
                                     "entity": "Italy"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                        "entity": "Japan",
                          "Japan": [
                             {
                                    "count": 1,
                                    "entity": "Japan"
                             }
                          ],
                        "currency": "Yen (JPY)"
                    },
                    {

                        "entity": "South Korea",
                          "South_Korea": [
                              {
                                    "count": 1,
                                    "entity": "South Korea"
                                }
                          ],
                      "currency": "Won (KRW)"
                    }
              ]
        },
        {"count": 5,
              "entity": "Persons",
              "Persons": [
                    {
                         "count": 2,
                        "entity": "Dodge"
                    },
                    {
                        "count": 1,
                        "entity": "Dodge Avenger"
                    },
                    {
                        "count": 1,
                        "entity": "Major League"
                    },
                    {
                        "count": 1,
                        "entity": "Sterling Heights"
                    }
              ]
        }
  ]

}});

I want to add the key value "Entity" in all levels to an array using recursion,

I'm able to collect the data from first level using the string

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="dataDumper.js"></script>


<script type="text/javascript">

var testJSON = {"Categories": 
{
"Facets": 
    [
    {
    "count": 1,
    "entity": "Company",
    "Company": 
            [
            {

            "entity": "Ford Motor Co",

            "Ford_Motor_Co": 
                [
                    {
                    "count": 1,
                    "entity": "Ford"
                    }
                ]
            }
            ]
    },
        {
            "count": 4,
            "entity": "Country",
              "Country": [
                    {

                        "entity": "Germany",
                         "Germany": [
                                {
                                    "count": 1,
                                    "entity": "Germany"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                         "entity": "Italy",
                        "Italy": [
                                {
                                     "count": 1,
                                     "entity": "Italy"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                        "entity": "Japan",
                          "Japan": [
                             {
                                    "count": 1,
                                    "entity": "Japan"
                             }
                          ],
                        "currency": "Yen (JPY)"
                    },
                    {

                        "entity": "South Korea",
                          "South_Korea": [
                              {
                                    "count": 1,
                                    "entity": "South Korea"
                                }
                          ],
                      "currency": "Won (KRW)"
                    }
              ]
        },
        {"count": 5,
              "entity": "Persons",
              "Persons": [
                    {
                         "count": 2,
                        "entity": "Dodge"
                    },
                    {
                        "count": 1,
                        "entity": "Dodge Avenger"
                    },
                    {
                        "count": 1,
                        "entity": "Major League"
                    },
                    {
                        "count": 1,
                        "entity": "Sterling Heights"
                    }
              ]
        }
  ]

}};

function scan(obj)
{
    var k;
    if (obj.hasOwnProperty('entity')) {



        for (k in obj){
           if (obj.hasOwnProperty(k)){


                scan( obj[k] );  


            }                
          }
    } 


    else{
        if(k=='entity')
        {
        alert(obj.entity);
   }
    }


};

scan(testJSON);



</script>
</head>

<body>

</body>

</html>

How do I get in to the inner levels for JSON string using recursive functions?

share|improve this question

50% accept rate
Dont put an else in, put the if and alert before the call to scan – El Ronnoco May 6 at 15:32
Thumbs up!!! And thanks a lot!!!! Really appreciate all your help.. – user1371896 May 6 at 23:14
@ElRonnoco Ive been experimenting with this thing and do u knw hw we cn add entities in different levels in to same array.. ie entities in level 1 goes to one array, level 2 to nxt and so on.. – user1371896 May 7 at 3:47
I'm not clear what you mean. You can add any new property to a Json object just by saying eg Main.new=1 will create a property 'new' in object Main. If you want to create a new Json object use {}. To create an array use []. to add a Json object to an array use myarray.push({}). To add an array to an array use myarray.push([]) – El Ronnoco May 7 at 11:21
with out using "key", do you know how to perform the same operation using array... – user1371896 May 7 at 11:24
feedback

2 Answers

up vote 0 down vote accepted

I have made a jsfiddle which traverses every object,array and value in the JSON like so...

function scan(obj)
{
    var k;
    if (obj instanceof Object) {
        for (k in obj){
            if (obj.hasOwnProperty(k)){
                //recursive call to scan property
                scan( obj[k] );  
            }                
        }
    } else {
        //not an Object so obj[k] here is a value
    };

};

I get no recursion error (in Chrome). Can you use this to do what you want?

If you need to test if an object is an array use if (obj instanceof Array)

To test if an object has an "entity" property use if (obj.hasOwnProperty('entity'))

To add (or modify an existing) "entity" property use obj.entity = value or obj['entity'] = value

share|improve this answer
I've answered this on my iPhone so if someone could fix my formatting i'd be very grateful!!! – El Ronnoco May 5 at 8:22
its showing the error,if is nt defined for If (h.hasOwnProperty(k)) – user1371896 May 5 at 8:24
Ah you may new to test for 'if (h instanceof object)' before entering the loop. – El Ronnoco May 5 at 8:30
no,,,it ws the format of ur code...I was in big letter.. It now alerts first entity Company and then shows "too much recursion " for getEntities(h[k]); – user1371896 May 5 at 8:32
1  
The "stop expression" is the one I used in my answer: if ( ({}).toString.apply( prop ) === '[object Object]' ) {. Btw, Object.keys returns an array of the enumerable properties, so it is not needed to use hasOwnProperty. – Florian Margaine May 5 at 9:09
show 14 more comments
feedback
(function recur( obj ) {
    Object.keys( obj ).forEach( function( prop ) {
        // Check if the property is an object
        if ( ({}).toString.apply( prop ) === '[object Object]' ) {
            // If it is, recall this function
            recur( prop );
        }
    } );
} () );

I haven't added your logic, but you get the idea of how to recursively traverse your object.

share|improve this answer
lemme give this a try...will give u a feedback aftr that.. – user1371896 May 5 at 7:56
how do I add the value of subobj here for the above example? – user1371896 May 5 at 7:57
What? I don't understand your comment. – Florian Margaine May 5 at 7:58
I didnt get what subobj is.. – user1371896 May 5 at 8:04
Oops, edited my answer correcly. The subobj is the property of the object that is an object, so you can traverse it too. – Florian Margaine May 5 at 8:04
show 7 more comments
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.