What's the point of having your values inside an array? It's redundant because you have a single object in them. You could remove the square brackets and just have this:
{
"data1": {
"key": "iohiohio",
"key1": "jhuihuj"
},
"data2": {
"key4": "hoih",
"key5": "kjhi"
}
}
Then, you would loop it like this:
fs.readFile(file, function(err, obj) {
for (var k in obj.data1) {
console.log(k + ": " + obj.data1[k]);
}
});
That would print only the keys in data1
, though! To print everything, you should use:
fs.readFile(file, function(err, obj) {
try {
obj = JSON.parse(obj);
} catch(e) {
console.log("Error while parsing");
return;
}
for (var k in obj) {
for (var k2 in obj[k]) {
console.log(k + " - " + k2 + ": " + obj[k][k2]);
}
}
});
// Result
// data1 - key: iohiohio
// data1 - key1: jhuihuj
// data2 - key4: hoih
// data2 - key5: kjhi
Edit: you should parse obj
. It's also better to put it in a try catch block in case the JSON is wrong and couldn't be parsed.
You can also check this, you could load the json with require
:
var obj = require("./jsonfile");
for (var k in obj) {
for (var k2 in obj[k]) {
console.log(k + " - " + k2 + ": " + obj[k][k2]);
}
}