Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with an API in javascript which uses IDs above JS max integer

I am building a Node backend which pulls data from the Vine API, and returns this to my front end. The IDs for posts and users are of type Number, and they frequently exceed the maximum integer that javascript can support, according to this question.

An example ID from the API is 934416748524998656. When I use JSON.parse on the front end it replaces those last 2 digits with 0, because it can't read a number that high This causes problems when I try to talk to the API with specific IDs, as it now doesn't recognise the ID.

Is there anything, short of creating a new service in another language, that I can do to work with these IDs? I tried using toString() to interpret the numbers as strings instead, but that just creates a string of the already malformed number.

Thanks for any help

like image 481
Jonathon Blok Avatar asked Aug 12 '14 16:08

Jonathon Blok


1 Answers

change the number into a string before parsing:

var responseData = JSON.parse(
   strJson.replace(/\: (\d{17,}),/g,': "$1",')
);

note this will falsely modify any string data that contains a big number that looks like a json value, but i'd call that a worthy tradeoff compared to the deep-investment alternatives. still, it's not just a big number that hits, but (": " + theNumber +","); the only time i can imagine that happening is someone "re-tweeting" the JS-invalid API response. use a parser if you care that much about being perfect.

like image 59
dandavis Avatar answered Sep 29 '22 06:09

dandavis