1

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.

4
  • 2
    the response you are getting is probably a string. you'd have to do something like JSON.parse(body) first Commented Mar 7, 2019 at 23:45
  • looks like your body isn't actually that object, but a JSON (string) representation. Try JSON.parse on it first. Commented Mar 7, 2019 at 23:45
  • Thanks guys! Like the everyone mentioned its a string. I was a able to use the solutions given below. Commented Mar 8, 2019 at 0:01
  • Related: Access / process (nested) objects, arrays or JSON Commented Mar 8, 2019 at 0:14

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Nitpick: The return value of JSON.parse is not JSON
1

body 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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.