JavaScript's GET method fails to retrieve the complete JSON file

I am facing an issue with a substantial JSON file that my JavaScript code is unable to pull in entirely. When I check the Network tab in Firefox developer tools, it shows that the data stops at around line 57,301 out of 528,342 lines in the JSON file.

Initially, I attempted to fetch the data directly but encountered errors related to the necessity of using 'await' alongside asynchronous functions, which I am not well-versed in. For my xmlhttp request, I had set the async flag to false as it was the only way I could make it work with my current code.

The JSON objects I am trying to retrieve contain latitude, longitude, and altitude information, structured as follows:

{"points":[
{"lat": 0, "lon": 0},
.
.
.
{"lat": 0, "lon": 0}]}

Here's how my request is currently coded:

function get_json_data(){
var data = [];
var response = new XMLHttpRequest();
response.onreadystatechange = function(){

     data_points = JSON.parse(this.responseText);
     *** CONVERTING LAT/LON TO ARRAY AND PUTTING INTO DATA ***

});
response.open("GET", "http://url/path/to/json", false);
response.send();

return data;
}

While this approach works smoothly for smaller JSON files, say around 10,000 lines, I'm struggling to handle much larger files containing over 500,000 lines. Any suggestions on how I can successfully process such massive JSON files?

Answer №1

When dealing with JSON data of any size, it is recommended to handle the operation asynchronously, especially if you are fetching it from an external source such as an API or file system. Consider giving the fetch() method another chance for this task. Unfortunately, platforms like jsbin and jsfiddle may restrict calling external APIs due to security concerns, making it difficult to provide an interactive demo. Here is a sample code snippet for your reference:

async function fetchData() {

    const response = await fetch('<url here>');
    const jsonData = await response.json();

    // Perform actions with JSON data

}

========== OR ==========

function fetchData() {

    fetch('<url here')
        .then(res => res.json())
        .then(data => {
            processData(data);
        });

}

The Fetch API will return a response that requires handling (e.g., checking for 200 OK status). In this scenario, ensure that upon successful request verification, you convert the response into a JSON object before further manipulation.

For extremely large files, utilizing Streams might be necessary. The Fetch API supports this functionality, refer to this example for implementation details: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams

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

Achieved anchoring an object to the top of the page while scrolling

Recently, I've been working on a piece of code to keep my div fixed at the top of the page while scrolling. However, it doesn't seem to be functioning as intended. Would anyone be able to point out where I might have gone wrong? The element in ...

"Activate the parent window by navigating using the accesskey assigned to the href

I have integrated a bank calculator tool into a website. The calculator opens in a new window, but I am encountering an issue. Users need a shortcut to open the calculator multiple times. I have discovered the accesskey feature, which works the first tim ...

Is it possible to receive both errors and warnings for the same ESLint rule?

My team is currently in the process of refactoring our codebase, utilizing ESLint to pinpoint any lint errors within our files. Initially, we set high thresholds in one .eslintrc file and have been gradually decreasing these limits as we enhance specific f ...

jQuery is unable to locate the FireBreath object

Currently, I am in the process of developing a web video player by using Firebreath to compile my C/C++ codec as a browser plugin. The plugin has been successfully loaded and is functioning properly (start, stop video, etc.). My next goal is to enable full ...

Three.js dynamic bone animation: bringing your project to life

Can transformations be applied to the bones of a 3D model in three.js to create a dynamic animation? I attempted to move and rotate the bones of a SkinnedMesh, but the mesh did not update. loader = new THREE.JSONLoader(); loader.load(&apos ...

1. Catalog of dual JSON inquiries2. Compilation of

I am struggling to understand the right way to proceed. When I run this query, I receive a JSON response containing file names: $.getJSON("http://api.server.com/my/?callback=?", function(data){ var results = []; $.each(data['resul ...

Ways to transfer Material-UI FlatButton CSS to a different Button element

I've recently incorporated a loading button object into my website from (https://github.com/mathieudutour/react-progress-button), and now I want to customize it using the Material-UI FlatButton CSS. However, I'm not quite sure how to achieve this ...

Capturing a JSON file directly from a web browser for integration into a Visual Basic 6 application

In Firefox (or any other browser), I can retrieve data every six seconds from a device called Saturn South ESBox on my local LAN by visiting "http://esbox/api/devices". This data is in JSON format. However, manually copying this file every minute for 24 ho ...

Can we expect React's useState to wait before executing subsequent logic, or will it immediately update the state and trigger a re-render

I have a specific scenario in my code where I am using the useState setter function in React to update a value on line 5. Everything seems to be functioning well without any errors, but I'm curious about something. Since setState updates the state and ...

Jackson encounters difficulty when trying to serialize Joda DateTimeFormatter

I'm having trouble returning a JSON response in my Spring MVC 3 application, specifically with Joda's DateTimeFormatter. com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.joda.time.format.DateTimeFormat$Style ...

Utilizing Selenium to inject javascript permanently or on every page refresh

In my selenium webdriver test using Python 3, I have implemented a semi-automated process. This means that some routines are automated while other tasks require user interaction with the browser, such as page refreshes or redirects. My challenge is to inj ...

The dynamic rendering of datasets is not supported in Material UI's <TableCell> component

I'm currently working on a table component that dynamically renders an item list based on a dataset. The Table component is made up of <TableHead/> and <TableBody/>. I am using the .map() method to dynamically assign values to the <Tabl ...

Unfortunately, the server experienced a temporary error and was unable to fulfill your request at this time

When testing the Google Speech API for the first time, I followed the example provided in Google's demo and it was successful. { "config": { "encoding":"FLAC", "sample_rate": 16000, "language_code": "en-US" }, "audio": { ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

Ways to develop a dynamic HTML TransferBox featuring a custom attribute

I am in need of developing a customized transferbox using HTML, JavaScript, and JQuery. The user should be able to select from a list of options and associate them with attributes. This selection process should involve transferring the selected options be ...

Error: Unable to initialize monthSelectPlugin as a constructor while trying to utilize the Flatpickr plugin

I'm trying to incorporate the monthSelectPlugin for flatpickr in a Rails application. I have it specified in my importmap like this: pin "flatpickr/dist/plugins/monthSelect", to: "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/emai ...

Repeating X and Y Axis Labels on Highcharts

Highchart is new to me. I recently created a basic chart showing the count of males and females over the past five years. I have included a screenshot for reference. I am wondering if it's possible to remove duplicate labels from both axes? Below is ...

Struggling with loading external scripts within background.js in Chrome extensions?

I am facing an issue with my chrome extension. I am unable to call an external script, specifically the ethereum script (web3.min.js), from within my background.js file. The error message I receive is: Uncaught EvalError: Refused to evaluate a string ...

Authorization missing in Select2 Ajax request

Encountering an issue while attempting a get request to a secure endpoint that requires an Auth token. Despite fetching the token asynchronously from chrome.storage, it fails to be included in the ajax request and results in a 401 error ("Authorization hea ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...