-2

I need to parse json data using jquery parseJSON as following JSON data :

{
    "0": {
        "0": "Item 1",
        "1": "",
        "2": "",
        "3": "",
        "4": "",
        "5": "",
        "childs": {}
    },
    "1": {
        "0": "Item 2",
        "1": "",
        "2": "",
        "3": "",
        "4": "",
        "5": "",
        "childs": {
            "0": {
                "0": "Item 2 - Sub 1",
                "1": "",
                "2": "",
                "3": "",
                "4": "",
                "5": ""
            },
            "1": {
                "0": "Item 2 - Sub 2",
                "1": "",
                "2": "",
                "3": "",
                "4": "",
                "5": ""
            }
        }
    }
}

I'm not familiar of json data structure, I didn't find any way to read values when indexed by numeral keys and I didn't know how to read childs sub values.

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71

1 Answers1

2

Use the parseJSON method to parse the string into an object:

var o = $.parseJSON(s);

Then you can access the properties with numerical names using the bracket syntax. For example, getting the item named "1", then the childs property from that, then the child named "0" and it's property named "0":

var item = o["1"].childs["0"]["0"];

With your example data, the variable item now contains "Item 2 - Sub 1".

Demo: http://jsfiddle.net/s4HLs/


To loop through all items you can use the each method. Example:

$.each(o, function(i, v){
  console.log(v["0"]);
});

This would write this to the console:

Item 1
Item 2

To loop through subitems you would nest loops. Example:

$.each(o, function(i, v){
    console.log(v["0"]);
    $.each(v.childs, function(j, c){
        console.log(c["0"]);
    });
});

This would write this to the console:

Item 1
Item 2
Item 2 - Sub 1
Item 2 - Sub 2

Note that there are no subitems for the first item, as that object is empty.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005