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?
obj[0]?obj[0]?{ ... }) use key based indexes, which means if you want to get"value"you need to reference it by it's key:obj["key1"]orobj.key1, you can only used numeric indexes when using Arrays:[ .. ]