Javascript doesn't parse large amount in JSON correctly

I am transmitting a list of approved tweets from a web server in JSON format. When I go to the URL: http://localhost:8000/showtweets/?after_id=354210796420608003 in my browser, I get the following JSON:

  [{ "date": "2013-07-08T12:10:09", "text": "#RaspberryPi ist auf dem Weg :-)", "author_pic_url": "http://a0.twimg.com/profile_images/1315863231/twitter_normal.jpg", "id": 354210796420608004, "author": "switol" }] 

Which has identifier: 354210796420608004 .

When I make a GET call from Javascript, the number changes:

 function TweetUpdater() { } TweetUpdater.latest_id = 0; TweetUpdater.undisplayed_tweets = new Array(); TweetUpdater.prototype.get_more_tweets = function () { // var since_id = parseFloat(TweetUpdater.get_latestlatest_id; // alert(since_id); var get_tweets_url = "/showtweets/?after_id="+TweetUpdater.latest_id; $.get(get_tweets_url, function (tweets) { if (tweets.length > 0) { ///////////////////////////////////////////////////////// alert(tweets[0].id+", "+ tweets[0].text); <<<<< THIS LINE ///////////////////////////////////////////////////////// TweetUpdater.latest_id = tweets[0].id; for (var i = 0; i < tweets.length; i++) { TweetUpdater.undisplayed_tweets.push(tweets[i]); } } }, "json"); }; 

This code warns: 354210796420608000, #RaspberryPi ist auf dem Weg :-)

354210796420608004! = 354210796420608000

Very strange.

+7
json javascript
source share
2 answers

No, not very strange. JS represents all numbers as doubles, and as integers grow, you lose accuracy at some point. See What is the maximum JavaScript integer value Number can contain without loss of precision? for details.

To solve the problem, just create the line id a - you still do not perform calculations with it. You will have to do this in the original JSON, although otherwise the loss accuracy occurs when JSON.parse narrower.

+11
source share

Try using id_str instead of id when using twitter API, it should work. see https://dev.twitter.com/discussions/11284 .

+2
source share

All Articles