Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Update Now with the help from @SergeyK and others, I have modified my above code as follows

var string = '{"key1": "value1", "key2": "value2", "key3": {"key31":"value 31"}}';

var obj = JSON.parse(string);
var array = Object.keys(obj)

for (var i = 0; i < array.length; i++) {
    console.log(array[i], obj[array[i]]);
}

And the output is as follows

$ node try.js 
key1 value1
key2 value2
key3 { key31: 'value 31' }

But for {"key31":"value 31"} how would I access key key31 and get its value value 31?

like image 425
Joel Divekar Avatar asked Jan 06 '23 12:01

Joel Divekar


2 Answers

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' }
like image 52
SergeyK Avatar answered Jan 13 '23 09:01

SergeyK


When you tries to access

 console.log(obj[0]);

You are actually trying to refer element at very first memory location in an array, but var string is a hash not array. Thats why you are getting undefined.

like image 41
Ashu Jha Avatar answered Jan 13 '23 08:01

Ashu Jha