What is the best way to extract the initial n rows of a JSON String array using JavaScript?

Currently, I am working with a JSON string that represents an array.

arrayString = "[
  { fName: 'John', lName: 'Doe'},
  { fName: 'Jane', lName: 'Doe'},
  { fName: 'Josh', lName: 'Doe'},
  { fName: 'Jack', lName: 'Doe'},
  { fName: 'Jill', lName: 'Doe'},
  { fName: 'Josh', lName: 'Doe'},
  { fName: 'Jean', lName: 'Doe'},
  { fName: 'Jake', lName: 'Doe'},
  { fName: 'Judy', lName: 'Doe'},
  { fName: 'Jery', lName: 'Doe'},
]";

I am facing an issue where parsing all the elements in one go using .json() method is causing high memory consumption due to the sheer volume of data. To address this, I am looking for a solution to parse only the first n rows from the array, mimicking client-side pagination for retrieving data efficiently from the string. However, it's important to note that I have no control over how this extensive dataset is sent from the server.

Answer №1

This issue could be addressed server-side through proper API design, but another approach is to consider utilizing range requests. By using range requests, specific portions of the data can be requested, avoiding potential corruption in the final fragment and ensuring that the client does not unnecessarily store large amounts of data.

If you prefer parsing segments of the complete dataset already stored on the client side, ES6 (ES2015) generators offer an ideal solution:

/**
 * This generator yields a specified number of records at each iteration.
 * @param {string} data          The data from which to extract records.
 * @param {number} n             Number of objects per yield.
 * @yield {string} Array containing the specified number of objects represented as a valid JSON string.
 */
function* getNRecords(data, n) {
  let index = 0;
  while (index < data.length) {
    let result = data.substring(index).split('}', n).join('}');
    
    result = result.endsWith('}]') ? result : result + '}]';
    result = index > 0 ? '[' + result.trim() : result; // Ensure it starts with '['
    
    index += result.length;
    yield result;
  }
}

/* === EXAMPLE === */

const exampleData = '[{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}, {g: 7, h: 8}]';
const batchSize = 3;

for (let nRecords of getNRecords(exampleData, batchSize)) {
  console.log(nRecords); // Additional parsing can be done here
}

The extraction of up to N objects occurs in this line:

data.substring(index).split('}', n).join('}');
.

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

Display or conceal a div based on checkbox selection

I am trying to implement functionality to show/hide a div when a single checkbox is selected. Currently, it works with "Select all" but I am struggling to make it work with a single checkbox. Below is the code for "Select All": JS: <script language=&a ...

Is it possible to update the state before initiating an API call that relies on that specific state in React?

useEffect(() => { resetState(); if (page === 'ADMISSION') { fetchAdmissionKitPosts(); } else if (page === 'WEEKLY') { fetchWeeklyKitPosts(); } else if (page === 'FESTIVAL') { fetchFestivalK ...

What steps can I take to address the issue of missing modules in an Angular application?

I am facing an issue with my Angular application where I am using two local libraries. Despite having all dependencies declared and imported correctly, the build process continues to throw errors related to missing modules. To give you a better picture of ...

I am eager to showcase a Pokémon image sourced from the API, but I am faced with the challenge of only having the image URL and not knowing how to display it effectively

As a beginner in programming, I am seeking some assistance. I have been able to retrieve a random Pokémon from an API and gather its data, including the ID, name, and picture. My main focus now is to display the image of the Pokémon in the custom modal I ...

Array in JavaScript containing a replica set of Node.js and MongoDB

As a novice programmer with more experience in sysadmin work, I've been tasked with setting up a new HA environment for a node js application using MongoDB. The current setup utilizes mongojs and monq java classes with only one MongoDB instance. In or ...

Retrieve information from a column containing a JSON object

I am working with a SQL-server where some data is stored as a JSON object in a table. ID Date Customer details 1 2022-01-01 {'Country':167,'AccountNumber':'123456','SwiftBic':'ABC123'} 2 2022-01-0 ...

What is the best way to manage a promise's response?

I'm currently facing a situation where I need to create a petition to an endpoint and retrieve the URL of the backend that I intend to use. My setup involves a file with the API configuration where I instantiate axios. Previously, my approach was sim ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

Executing an executable using Python's JSON module

I'm currently dealing with an executable binary file that can be executed through the terminal or by using Python code. $`python3 shell_c.py` The Python file contains the following: import subprocess def executable_shell(): x=subprocess.run(&ap ...

What is the best way to reset the values in react-multiple-datepicker?

Having trouble clearing values assigned in react-multiple-datepicker library. import MultipleDatePicker from "react-multiple-datepicker"; import React from "react"; class Addjob extends React.Component { constructor(props) { super ...

Add a data attribute to an HTML element within JSX without assigning any value

Initially, I encountered a challenge when attempting to add an attribute to a custom element/component. I found that I could only add it to non-custom elements such as div and input. https://codesandbox.io/s/react-16-966eq const dAttribute = { "data-rr-m ...

Tips for removing or changing the X-Powered-By header in a Sails.js application

Running a Sails.js application results in the automatic addition of the HTTP header X-Powered-By: "Sails <sailsjs.org>" to every response. Is there a way to prevent or modify this header? ...

What steps can I take to troubleshoot and fix the height of a div/span element?

Here is my HTML code: <div> <span style="display: inline-block;height:20px">20</span> <span style="display: inline-block;"><img src="img/ex.png"/></span> </div> The image I have in the second span is sized at ...

PHP code to fetch and parse XML exchange rate feed

I am having trouble with using the currency exchange rate feeds provided by the European Central Bank (ECB) Despite following their documentation on parsing the xml, none of the options seem to work for me. I have confirmed that my settings have allow_ur ...

When the month changes in the React AntDesign Calendar Component, it automatically selects the last chosen day

My goal is to store the selected day in the state when a user clicks on a specific date. However, I am encountering an issue where the previously selected day remains saved in the state even after changing the month. Upon logging the onSelect event to the ...

Guide on iterating through a JSON array in Python and inserting it into a PostgreSQL database

I'm facing a dilemma where the potential solutions I come up with seem to lead to convoluted code. Currently, I have the following JSON data in Python 3 that I need to insert into a PostgreSQL database. { "name": "test", "country": "DE", ...

Navigate the user directly to the page where the event date aligns with today's date for easier access to relevant events

I have a function that retrieves posts, but I want users to be directed to a page where posts have a date of "today" that is not the event's publish date but the date when the event is happening. For example, if I have events with a man_date field of ...

IE is failing to display the textarea, but it is successfully getting submitted

I've written a function in jQuery and JavaScript that generates a form element: createEmail: function(title){ var $emailForm = $('<form>',{action: 'sendEmail.php', id: 'emailForm'}); var $table = $( ...

The content in ACF appears to be missing when displayed in the fancybox

I have configured ACF to appear in a fancybox. The fields are being pulled in (as I can see the hardcoded header information), but nothing from the ACF appears. I have linked it to call an ID, which is then associated with the section that should be displa ...

Is there a way to disable a dropdown menu when clicking on a different one?

[![ Dashboard Admin Admin Profile Change Password Doctors Doctors List Doctors Appointments Doctors Requests Add a Doctor Patients ...