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.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
jr0531
  • 25
  • 1
  • 1
  • 3
  • 2
    the response you are getting is probably a string. you'd have to do something like JSON.parse(body) first – JV Lobo Mar 07 '19 at 23:45
  • looks like your `body` isn't actually that object, but a JSON (string) representation. Try `JSON.parse` on it first. – Robin Zigmond Mar 07 '19 at 23:45
  • Thanks guys! Like the everyone mentioned its a string. I was a able to use the solutions given below. – jr0531 Mar 08 '19 at 00:01
  • Related: [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Mar 08 '19 at 00:14

2 Answers2

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);
KevBot
  • 17,900
  • 5
  • 50
  • 68
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);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79