JSON, getting data

I'm new to JSON and trying to figure out how to get info from a JSON string.
Another question, isn't this not a valid JSOn format, I thought that there needs to be starting ' and ending ' for json files.

In my fiddle, I placed indicators of what I'm trying to get:

fiddle: http://jsfiddle.net/hFTN8/37/

var input = {
    "name": "positive", //get this value
    "children": [{
        "name": "product service",
        "children": [{
            "name": "price",
            "children": [{
                "name": "cost",
                "size": 8
            }]
        }, {
            "name": "quality",//Get this value
            "children": [{
                "name": "messaging",
                "size": 4
            }]
        }]
    }, {
        "name": "customer service",
        "children": [{
            "name": "Personnel",
            "children": [{
                "name": "CEO",//get this value
                "size": 7
            }]
        }]
    }, {
        "name": "product",
        "children": [{
            "name": "Apple",
            "children": [{
                "name": "iPhone 4",
                "size": 10
            }]
        }]
    }]
}
console.log(JSON.input.name[0]);

Answers 1

  • JSON is a format for storing data.

    You can convert the JSON string to JS object as follow.

    var javascriptObject = JSON.parse(yourJsonString);
    

    Now let's assume yourJsonString is your code snippet.

    To get the value of key "name" try console.log(javascriptObject.name);

    "children" is an array of 3 objects. You can access the array objects as follow.

    var arrayObject=javascriptObject.children[indexValue];
    

    You can get the value of key from javascript object using "." operator.

    http://www.w3schools.com/js/js_json.asp

    First value can be accessed using : javascriptObject.children[0].children[1].name;

    Second value can be access using : javascriptObject.children[1].children[0].children[0].name;


Related Articles