-1

I refer to many sites about recursion of json as below

JavaScript recursion does not work properly
jQuery recursive iteration over objects

but most of them either knows the key or iterate using know keys. Also $.each work wells if key & value are both string such as {"firstname" : "lastname"} & then function (k,v) can give key & value as k & v respectively.

But in case if json object is complex & we do not whats coming that is key can be any for example in JSON1 & JSON2 are different in keys one, three, two in JSON1 is replaced by five, six & ten in JSON2 response.

JSON1

{
    "one": true,
    "three": [
        "red",
        "yellow",
        [
            "blue",
            "azure",
            "cobalt",
            "teal"
        ],
        "orange"
    ],
    "two": 19.5
}

JSON2

{
    "five": true,
    "six": [
        "red",
        "yellow",
        [
            "blue",
            "azure",
            "cobalt",
            "teal"
        ],
        "orange"
    ],
    "ten": 19.5
}

If some how we can know the key name & then compare it would be ok. easier to compare the keys, for this tagName should be work as suggested in URL below

Can jQuery provide the tag name?

But for normal json object attribute tagname does not seem to work. Inspecting in firefox attributes such as text(), attr(), does not get me tagName. What I want is to loop through the json object (in practice i am using xml2json plugin to convert xml into above json format) & compare key if exists and do action. I know in XML you can do the same by using nodeName. How should I do the same using JSON object.

Community
  • 1
  • 1
user593029
  • 511
  • 7
  • 18
  • Still I'm not sure that I got this question, but maybe you're talking about something like JSON pointers (aka XPath for JSON)? In that case, perhaps [this library](http://goessner.net/articles/JsonPath/) might be helpful? – raina77ow Jul 03 '12 at 16:26
  • For ex, if you are iterating html table that has row and cells you can write 3 loops with for each table, each row & each cells but what if each cell has table inside it. However here you know there are definite three tags table, row, & cell but if JSON object elements can come in any order as given above in JSON1 & JSON2 & you are iterating it how would you knowing what is current element without know the tagName. So if JSON object structure & elements (key, val) structure changes how can one know which current key & hence its children is processed – user593029 Jul 03 '12 at 16:34
  • It doesn't matter how many rows and columns your table has. The point is it has _rows_ and _columns_; so your iteration will always be two-levels deep. – raina77ow Jul 03 '12 at 16:37
  • How do i know whether it is row or column or table inside a cell?? During iteration & depending on whether table, row or cell is processed I want to operate differently. Also what if keys are changed as in JSON1 & JSON2 how do I know which key i am currently processed.. In the fiddle example if the same div structure is converted into div json object & then you use$.each how will we know if the key is div & not something else. Also if the div structure contains paragraph, span tag etc & you want to act separately say color is changed for that tag how to do if we do not know the tagName. – user593029 Jul 03 '12 at 16:52
  • As I said in xml/dom parsing nodeName is available & comparing that we know the node type currently processed but what if we have json object itself instead of DOM or XML & iterating throught json object – user593029 Jul 03 '12 at 16:54

2 Answers2

0

I'm not entirely sure what you're looking for, but I will throw this out here.

If you use something such as for (key in jsonObj) { ... } then you can iterate through the object without knowing the key name. Inside the loop, key will give you the current key name and jsonObj[key] will give you the corresponding value.

For example, if we use your "JSON1" object:

for(key in JSON1) 
{
   alert(key + ": " + JSON1[key]);
}

The first alert will display: one: true.

I suspect that you can also make this recursive to access nested objects.

Jen
  • 586
  • 3
  • 12
  • I think this should work.. Thanks a lot. I tried $.each but that does not work.. & give me correct key it rather gives me number 0. – user593029 Jul 03 '12 at 17:01
  • Lastly how would you know number of attributes associated to the object for example if table has property width, height which can be accessible as table.width & table.height using dot access member, but in my case i do not know which all combination can have i.e it can be table.x table.y etc. Also i do not know the name of the member it could be x, y, or z or nothing at all how can i do that – user593029 Jul 03 '12 at 17:14
0

A quick solution is to use jQuery.parseJSON http://api.jquery.com/jQuery.parseJSON/

Or you can do:

var obj = JSON.parse(JSON1);

JSON object, however, is not supported by all browsers, you might have to look at: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

including that library wouldn't have to change your code since it makes the JSON object global (in case the browser doesn't support it).

It takes your JSON string, parses it, and converts it into an obj So for JSON1 you would get something like:

obj.one giving you the value = true

obj.two giving you the value = ["red","yellow",["blue","azure","cobalt","teal"],"orange"]

obj.three giving you the value = 19.5

Then you can traverse through the obj properties:

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {        
        switch(prop){
        {
            case "one":
                //Do stuff here
                break;
            case "two":
                //Do stuff here
                break;
            case "three":
                //Do stuff here
                break;
        }
    }
}

Also, using obj[prop] will give you values rather than the names. Example, during the loop if you encounter that: prop = "three"

then:

obj[prop] = 19.5

sksallaj
  • 3,872
  • 3
  • 37
  • 58
  • I think this will work but can we do dynamically as well without using switch case & without using dot operator for example obj.one or obj.two will work if we know all combinations but what if we do not know the prop name itself. can we have arrays of all the attributes that can be accessed using index.. it is possible, not sure am going bizarre – user593029 Jul 03 '12 at 17:20
  • You would put be putting yourself in a corner. You can't blindfold your project by getting unexpected key values from a JSON object. The key to good code and design practice is knowing your inputs and keeping them consistent. – sksallaj Jul 03 '12 at 18:33
  • However, I can tell that your JSON format is consistent, so I'd get the position of the key rather than the name. If you know the first node of each JSON file is for something, as well as the second and third, you could simply do a count on the "for loop" and that could get you somewhere closer to what you probably want. – sksallaj Jul 03 '12 at 18:35
  • One more thing, I've notice you are having problems making the connection between JSON and HTML. You don't get html attributes from a JSON object. JSON helps collect data from html values like an input textbox or select box. To retrieve html attributes you'd have to learn some JQuery, like click() or change() and then attach with the "this" property. Of course this depends on where you get your json object or how it is built. But if you can get a way to pass your JSON data into a jQuery click() event, you can then compare html values with values within your JSON object. – sksallaj Jul 03 '12 at 18:46