This is how my response body looks like. Its stored in a variable and when i use console.log(body) I get the following.
[
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
]
Im trying to access "key3" using the following
console.log(body[0].key3)
I get undefined. Im not sure what is wrong here. If i just do
console.log(body[0])
im getting a string [
Thanks for your help here.
2 Answers 2
The Problem Explained
Your JS is looking at the property on a specific character:
Take a look at the following example that will help demonstrate what is going on:
const string = 'Hello';
console.log(string[0] === 'H'); // true
console.log('H'.key3 === undefined); // true
The Solution
You need to JSON.parse the string:
const body = `
[
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}
]
`;
const parsed = JSON.parse(body);
console.log(parsed[0].key3);
1 Comment
JSON.parse is not JSONbody sounds like it's a string - JSON.parse it to an object:
var body = '[{"key1": "value1","key2": "value2","key3": "value3"}]';
console.log(body[0]);
body = JSON.parse(body);
console.log(body[0].key3);
Comments
Explore related questions
See similar questions with these tags.
bodyisn't actually that object, but a JSON (string) representation. TryJSON.parseon it first.