1
[{"id":7,"message":"This is another test message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}]

That's my response. I try to get a datum. I have tried data.id but it fails and returns undefined.

Ram
  • 143,282
  • 16
  • 168
  • 197
ROB ENGG
  • 67
  • 1
  • 1
  • 7

4 Answers4

7

As I assume that you are working with a JSON string, you first have to parse the string into and JSON object. Else you couldn't reach any of the properties.

parsedData = JSON.parse(data);

Then you can get your property:

parsedData[0].id
  • There is no JSON string in the question. – Gerardo Furtado Aug 11 '16 at 15:21
  • Sorry, as he said he wants data from JSON I assumed that he is getting the data from an JSON file and then it would be a string.. –  Aug 11 '16 at 15:24
  • He is *probably* getting the data as a string (and that's why he said `console.log(data[0].id)` returned undefined and your answer worked), but we can only answer based on the question, and the question has only an array. – Gerardo Furtado Aug 11 '16 at 15:26
1

This seems to work just fine

var data = [{
  "id":7,
  "message":"This is another test message",
  "taker_id":"131",
  "giver_id":"102",
  "status":"0",
  "stamp":"2016-08-11"
}];
console.log(data[0].id);

https://jsbin.com/jewatakize/

Jonathan Newton
  • 832
  • 6
  • 18
0

if you just want to get the id from this one object then data[0].id will work just fine. If you expect to have multiple objects in that same array then you can use a loop. for example if this is angular you can do:

<div ng-repeat='info in data'>
    <p>{{info.id}}</p>
</div>

This will allow you to iterate through multiple objects within the array and get all id's.

Kerrin631
  • 198
  • 3
  • 13
0

The problem here is that you have here an array of objects, and you are trying to access it without indexing. You should first parse it using and then access the object by indexing

let objects = JSON.parse(data)
console.log(objects[0].id)
Leonel Kahameni
  • 793
  • 8
  • 10