Joel Divekar Joel Divekar - 3 months ago 98
JSON Question

Parsing nested JSON in Nodejs

I have been trying to parse nested JSON data and below is my code

var string = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}';
var obj = JSON.parse(string);
console.log(obj.key1)
console.log(obj[0]);


And this is the output

$ node try.js
value
undefined


Why I am getting undefined for
obj[0]
? How to get value in this case, and also for nested key
key31
?

Answer

You just can't access named object property by index. You can use obj[Object.keys(obj)[0]]

Edit:

As @smarx explained in the comments, this answer is not suitable for direct access to the specific property by index due to Object.keys is unordered, so it is only for cases, when you need to loop keys/values of object.

Example:

var string = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}';
var obj = JSON.parse(string);
var keysArray = Object.keys(obj);
for (var i = 0; i < keysArray.length; i++) {
   var key = keysArray[i]; // here is "name" of object property
   var value = obj[key]; // here get value "by name" as it expected with objects
   console.log(key, value);
}
// output:
// key1 value
// key2 value1
// Key3 { key31: 'value 31' }
Comments