Loading and parsing JSON #loadingandparsingjson
/* 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"
* }]
* }
*/