1

I use this API that returns a JSON with strings in values that are separated by colons.Example:

{
  "id": "test:something:69874354",
  "whatever": "maybe"
}

In this example I only need the numeric value of the identifier (69874354), but it could be that the value I'm after is a string (like 'something'). I've never seen this notation in APIs before and I know I could do something like:

var array = Object.id.split(':');
return array[array.length - 1];

...but it feels wrong and I'm thinking there is a standard behind this or a best practice I'm missing?

BoDeX
  • 846
  • 8
  • 18
  • 6
    There is nothing in JSON standards that attempts to deal with the *value* of a `string` property. You'll have to deal with it manually and it's completely fine. – haim770 Feb 07 '19 at 08:16
  • maybe you api offers some other flags to get another format? – Nina Scholz Feb 07 '19 at 08:16
  • Possible duplicate of [How to find a number in a string using JavaScript?](https://stackoverflow.com/questions/1623221/how-to-find-a-number-in-a-string-using-javascript) – adiga Feb 07 '19 at 08:17
  • @adiga thanks but although the example uses numbers, the question extends to all data types. – BoDeX Feb 07 '19 at 08:19
  • what's wrong with using `split`? Is there any "pattern" for the item you want to isolate? – molamk Feb 07 '19 at 08:21
  • 1
    @molamk nothing wrong really, just that I thought the notation looked like a sub-sub value, some JSON wizardry I wasn't aware off, but it seems not to be the case (as pointed out by haim770 so... I guess I'll go with split. – BoDeX Feb 07 '19 at 08:26
  • do you have in all properties this style or only in some? – Nina Scholz Feb 07 '19 at 08:31
  • @NinaScholz only some. – BoDeX Feb 07 '19 at 08:36
  • do you know the keys in advance? – Nina Scholz Feb 07 '19 at 08:37
  • @NinaScholz it seems the info I'm looking for is always at the end but that's only those that I've seen until now. The second value (between column 1 and 2) seems to almost always be a copy of the parent object's key. If we're in an array, the value would be singular but otherwise the same. – BoDeX Feb 07 '19 at 08:41

1 Answers1

0

The way you are doing it is correct, although it could be simplified:

return Object.id.split(":").pop();

Since as shown in the documentation for Array.prototype.pop, it returns the element popped from the array (the last element).

One suggestion with your code - don't use the name Object because that's reserved in JavaScript - use something else (object would be fine since JS variable names are case-sensitive).

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79