ROB ENGG
ROB ENGG

Reputation: 67

How to retrieve data from json data

[{"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.

Upvotes: 1

Views: 49495

Answers (4)

Leonel Kahameni
Leonel Kahameni

Reputation: 943

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)

Upvotes: 0

user3997955
user3997955

Reputation:

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

Upvotes: 8

Kerrin631
Kerrin631

Reputation: 198

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.

Upvotes: 0

Jonathan Newton
Jonathan Newton

Reputation: 840

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/

Upvotes: 1

Related Questions