Joel Divekar Joel Divekar - 1 year ago 377
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);

And this is the output

$ node try.js

Why I am getting undefined for
? How to get value in this case, and also for nested key

Answer Source

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


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.


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' }