0

An API returns a string of text that looks like this (xxx used for security):

{"xxx":{"xxx":{"xxx":{"xxx":{"results":[{"latest.GigabytesIngested":12641.824682336}]}}}}}

If I do this:

console.log(JSON.parse(body).xxx.xxx.xxx.xxx.results[0]);

I get this, which is fine:

{ 'latest.GigabytesIngested': 12641.82487968 }

My problem is I only want to grab the number. The below attempt doesn't work, maybe because there's a dot in the key name, or maybe because I'm just doing it wrong?

console.log(JSON.parse(body).xxx.xxx.xxx.xxx.results[0].latest.GigabytesIngested);
Jimmy D
  • 5,282
  • 16
  • 54
  • 70

2 Answers2

0

Yes, the period in the key is the problem. You need to use an alternate way to reference the key.

console.log(JSON.parse(body).xxx.xxx.xxx.xxx.results[0]["latest.GigabytesIngested"]);

or

var result = JSON.parse(body).xxx.xxx.xxx.xxx.results[0];
var lgi = result["latest.GigabytesIngested"];
console.log(lgi);
Janine White
  • 439
  • 5
  • 14
  • You even seem to have just copied my comment, because you have the same spelling mistake ... – derpirscher May 27 '22 at 16:45
  • @JimmyD Yes, a comment cant be accepted as answer. But copying someone else's comment (inclusive typo) as own answer is *VERY* discouraged ... – derpirscher May 27 '22 at 16:46
  • I see no way of accepting a comment as an answer. So if you post your comment as an answer I'll accept it. – Jimmy D May 27 '22 at 16:47
  • @JimmyD: There is no way of accepting a comment as answer. But tbh: I don't really care about reputation that much that I'd post an anwer to a question that probably has been asked hundrets of time on SO (I'm just to lazy to search for a duplicate). That's why I just put it in a comment. But I also really dont like, someone else trying to take the credit for my original comment ... – derpirscher May 27 '22 at 16:50
  • @derpirscher I read the question and was ready to give the same answer before I read your comment. I upvoted your comment anyway. A comment is not an answer. Next time enter the answer if you want credit for it. I also included alternate syntax to elaborate on how it worked. – Janine White May 27 '22 at 23:28
  • @JanineWhite You were ready to give the answer without reading my comment, and coincidentally you included the very same typo in your answer as I did in my comment? And as I already said, this question has been asked many times on SO, so it should be marked as a duplicate, instead of giving an answer ... – derpirscher May 28 '22 at 06:32
0

@derpirscher answered correctly in a comment:

console.log(JSON.parse(body).data.actor.account.nrql.results[0]['latest.GigabytesIngested']);
Jimmy D
  • 5,282
  • 16
  • 54
  • 70