root
root

Reputation: 177

Parse JSON file with JavaScirpt

I'm trying to parse a JSON file with JavaScript. I've managed to open a local JSON file with JavaScript and print the keys of it with this code. I can't figure out how to get the values of each key. I want to get the x, y, z values of each key and assign them to variables in JavaScript.

script.js

function loadJSON(callback) {

var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'js/data.json', true);
xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {

// .open will NOT return a value but simply returns undefined in async mode so use a callback
        callback(xobj.responseText);

    }
};
xobj.send(null);

}

// Call to function with anonymous callback
loadJSON(function(response) {
// Do Something with the response e.g.
var jsonresponse = JSON.parse(response);

// Assuming json data is wrapped in square brackets as Drew suggests
    var keys = Object.keys(jsonresponse);
    console.log(keys[0]);
});

data.json

{
  "a": {
    "x": "12",
    "y": "2",
    "z": "17"
  },
  "b": {
    "x": "8",
    "y": "2",
    "z": "21"
  },
  "c": {
    "x": "9",
    "y": "3",
    "z": "17"
  }
}

Upvotes: 0

Views: 96

Answers (2)

fiveobjects
fiveobjects

Reputation: 4327

As I mentioned in the comment, if you have accessed the top level keys (a, b, c etc.) then the next level (contained key-value pairs) can be accessed in the same manner.

raw = '{ "a": { "x": "12", "y": "2", "z": "17" }, "b": { "x": "8", "y": "2", "z": "21" }, "c": { "x": "9", "y": "3", "z": "17" } }';
data = JSON.parse(raw);
Object.keys(data).forEach(key => {
    value = data[key];
    console.log("Values inside: " + key)
    Object.keys(value).forEach(key => console.log(key + "=" + value[key]));
})

Since both levels are Map data structure, the same can be accessed this way as well: data['a']['x'], data['b']['x'] etc.

Upvotes: 1

William Gunawan
William Gunawan

Reputation: 750

Your result of json parse is a object so you just need to process it as object not array.

var jsonresponse = JSON.parse(response);

for(let data in jsonresponse) {
    for (let key in jsonresponse[data]) {
        let value = jsonresponse[data][key];
        console.log(key, value)
    }
}

Upvotes: 1

Related Questions