Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
25

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

[#60953] Friday, August 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ammonjesseg

Total Points: 170
Total Questions: 110
Total Answers: 98

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;