Error with JSON parsing in JavaScript when processing large numbers

After requesting a list of approved tweets from a webserver in JSON format, I visited the URL:

http://localhost:8000/showtweets/?after_id=354210796420608003
and received the following JSON response:

   [{
    "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"
}]

The tweet has an id of: 354210796420608004.

However, when I tried to retrieve more tweets using a GET call in Javascript, something strange happened:

function TweetUpdater() {
}

TweetUpdater.latest_id = 0;
TweetUpdater.undisplayed_tweets = new Array();

TweetUpdater.prototype.get_more_tweets = function () {
    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 unexpectedly alerts:

354210796420608000, #RaspberryPi ist auf dem Weg :-)

It seems that the ids are not matching up correctly:

354210796420608004 != 354210796420608000

A peculiar situation indeed.

Answer ā„–1

It's not too strange that you are experiencing precision loss in JavaScript when dealing with large integers since numbers are represented as doubles. For more information on this topic, check out What is JavaScript's highest integer value that a Number can go to without losing precision?.

If you want to address this issue, consider converting the id to a string instead of keeping it as an integer, especially if you are not performing calculations with it. Keep in mind that you may need to handle this conversion directly in your original JSON data to avoid precision loss during the JSON.parse process.

Answer ā„–2

For optimal functionality when utilizing the Twitter API, consider employing id_str in place of id. This adjustment should enhance performance. Additional information can be found here: .

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Display the precise outcome for each division following a successful AJAX callback

Iā€™m facing a challenge in getting individual results for each item after a successful AJAX callback. Currently, I am able to retrieve results, but when there are multiple items, all displayed results are being added to each div instead of just the corres ...

Sending a JavaScript click event using curl and PHP

Attempting to extract information from a website. The main page contains multiple option buttons along with an ACCEPT and RESET button. When the user selects options and clicks on the ACCEPT button, new content is displayed. I have a question regarding ma ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Button in HTML not functioning as expected

I have 3 different files that are crucial for my webpage to function properly: index.html: <html> <head> </head> <body> <h1>Webpage</h1> <p id = "text">Hello world!</p> <button oncl ...

JAVA JSON Template Integration

My task involves working with two JSON files. The first file, first.json, contains: { "sentence" : "{{place_name}} is {{adj}} place" } In the second file, second.json, we have: { "place_name" : "New York", "adj" : "a nice" } I am currentl ...

Tips for distinguishing individual submit buttons within a foreach loop

Here is my code snippet: <?php require_once 'core/init.php'; if($result = $db->query ("SELECT * from countries")) { if($count = $result->num_rows) { $rows = $result->fetch_all(MYSQLI_ASSOC); } ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

Firebase Operation Not Supported Error in next.js (auth/operation-not-supported-in-this-environment)

After successfully deploying a Next.js app hosted on Vercel with Firebase authentication that functions properly for users, I encountered a mysterious error during the "npm run build" phase: FirebaseError: Firebase: Error (auth/operation-not-supported-in ...

I am finding that the text I am creating using context.fillText keeps getting distorted within the canvas

I am attempting to place text inside a canvas element. The HTML markup for the canvas is as follows: <canvas id="leaderboard2" style="position: fixed; right: 1250px; top: 140px; width: 230px; height: 330px;"></canvas>. Des ...

Issue with Firefox browser: Arrow keys do not function properly for input tags in Twitter Bootstrap drop down menu

Requirement I need to include a login form inside the dropdown menu with username and password fields. Everything is working fine, except for one issue: Issue When typing, I am unable to use the arrow keys (up/down) in Firefox. This functionality works ...

Jolt - Self-contained entity- Iteratively substitute property identifiers

I'm new to working with Jolt. I have a JSON payload that represents logical conditions using AND/OR, and it can include an array of conditions called "conditionPredicates", leading to nested conditions like AND(OR(a, b ,c), OR(d,e)). I'd like to ...

This code snippet results in the property being unrecognized

I recently wrote this block of code and encountered an error while trying to run the alert function. It keeps telling me that 'this.words' is not defined. I suspect the issue lies within the jQuery portion, as I am able to access the array where ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Utilizing Async/Await with Node.js and Mongoose

Learning Promises and async/await programming is a new challenge for me, especially in the context of creating an API using Nodejs, Express, Mongoose, and MongoDB. While most tutorials focus on handling asynchronicity within a single file containing routin ...

Exploring the connections between Hibernate and AngularJS

I have established a connection between Travelers and Trips in Hibernate: https://i.sstatic.net/YQetP.png To create a new trip for traveler 1, I need to visit the route /frontend/#/trip-creation/1. Here, a form is available: https://i.sstatic.net/BeXnU. ...

Measuring the space between components

I am looking for a way to dynamically calculate distance on a canvas, similar to the example shown in the figure. I want to be able to drag the highlighted joints in order to adjust the span for calculating distances. Are there any plugins available for th ...

SmoothDivScroll jQuery Plugin may encounter issues when JavaScript files are loaded asynchronously

I recently encountered an issue with SmoothDivScroll when I attempted to load all the JS files asynchronously. I implemented my own async loading pattern using Lazyload.js by Ryan Grove. I also experimented with Modernizr's load/complete pattern, but ...