ibvasi
4/6/2017 - 9:16 PM

Loading and parsing JSON

Loading and parsing JSON

/* The JSON object served from myjson.com is
{
    "array": [{
        "red": "#f00",
        "green": "#0f0",
        "blue": "#00f",
        "cyan": "#0ff",
        "magenta": "#f0f",
        "yellow": "#ff0",
        "black": "#000"
    }]
}
*/
// Loading the JSON object
var requestURL = "https://api.myjson.com/bins/1h7zvf"; // myjson.com
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json'; // parses the JSON object
request.send();

request.onload = function() {
    var data = request.response;
    console.log(data); 
    console.log(data.array[0].blue) // #00f
}
/*
{
    array: [{
        red: "#f00",
        green: "#0f0",
        blue: "#00f",
        cyan: "#0ff",
        magenta: "#f0f",
        yellow: "#ff0",
        black: "#000"
    }]
}
*/

// OR

// Loading the JSON object
var requestURLOne = "https://api.myjson.com/bins/1h7zvf"; // myjson.com
var requestOne = new XMLHttpRequest();
requestOne.open('GET', requestURL);
requestOne.send();

requestOne.onload = function() {
    var dataOne = JSON.parse(requestOne.response); // Parses the JSON object
    console.log(dataOne); 
    console.log(dataOne.array[0].blue) // #00f
}
/*
{
    array: [{
        red: "#f00",
        green: "#0f0",
        blue: "#00f",
        cyan: "#0ff",
        magenta: "#f0f",
        yellow: "#ff0",
        black: "#000"
    }]
}
*/