20
rated 0 times
[
22]
[
2]
/ answers: 1 / hits: 26063
/ 8 Years ago, tue, august 23, 2016, 12:00:00
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
?
More From » json