0

Using js in a node environment with npm request.

I'm trying to grab Id from body.

Body:

[
  {
    "Id": 201801310058,
    "ItemType": 2,
    "SourceId": 2,
    "SourceUID": "4c45370f-a63d-4768-8772-03a7d7b364ff",
    "SourceName": null,
    "Duration": 16564,
    "Synchronized": false,
    "TimeStamp": "2018-01-31T18:01:03.7510329+01:00",
    "TrigValue": 0.0,
    "DataSize": 24766691,
    "Reindexed": false
  }
]

Without the square brackets it was easy using body["Id"].

What is the best practice in this case?

Edit:

Here's the whole code:

request('http://localhost:8124/Json/GetLastItems?sourceId=-1&numRecords=1&authToken=f3c6a605-7265-4a4d-922b-dd5c5f9966ee', function (error, response, body) {
    console.log(body[0].Id);
});

body[0].Id is undefined

Rune Aspvik
  • 145
  • 3
  • 13
  • 1
    Just `body[0].Id`. – Striped Jan 31 '18 at 17:52
  • 1
    Isn't `body` a string? Don't you have to use `JSON.parse(body)` to get an object/array out of it? – James Jan 31 '18 at 18:26
  • @James that is correct. So I tried var item = JSON.parse(body) and then item.Id. Still not working. – Rune Aspvik Jan 31 '18 at 18:39
  • body represents an array, so it would still need to be item[0].id – James Jan 31 '18 at 18:40
  • Still nothing: request('http://localhost:8124/Json/GetLastItems?sourceId=-1&numRecords=1&authToken=f3c6a605-7265-4a4d-922b-dd5c5f9966ee', function (error, response, body) { var item = JSON.parse(body); console.log(item[0].Id); }); – Rune Aspvik Jan 31 '18 at 18:50

2 Answers2

1

Because the body here is and array, to get the Id property, you'd need to use body[0].Id.

But if there's ever a chance that there's more than one object in the array, to get each of the Ids, you'd have to loop over the body:

for(let i = 0, l = body.length; i < l; i++) { console.log(body[i].Id); // gets the Id property of this specific object in body }

Micaiah Reid
  • 439
  • 3
  • 5
  • I'm still getting body[0].Id undefined. request('http://localhost:8124/Json/GetLastItems?sourceId=-1&numRecords=1&authToken=xxx', function (error, response, body) { console.log(body[0].Id); }); – Rune Aspvik Jan 31 '18 at 18:17
0

it seem to be an array so you should use

body[0].Id
JPRLCol
  • 749
  • 11
  • 28