Decoding arrays of JSON data

Receiving "chunked" data (json arrays) on the front-end via "xhr" (onprogress).

Handling delayed chunks is easy - just remember response length and offset. The challenge comes when multiple "chunked" responses arrive simultaneously, resulting in an unparsable final response due to incorrect json format.

Structure:

[array 1][array 2] ... [array N]

Example:

[{"response": [{"itemId": 1}]}][{"response": [{"itemId": 2}]}]

Question: How can this be parsed? Attempts with regular expressions failed when dealing with sub-arrays within response bodies, like in the example given above.

Current matching pattern:

1) {"response": [{"itemId": 1}
2) {"response": [{"itemId": 2}

Desired output:

1) {"response": [{"itemId": 1}]}
2) {"response": [{"itemId": 2}]}

Looking for alternative approaches or tweaks to the current regular expression:

\[(.*?)\]/gi

Any suggestions on using regular expressions or recommendations for different methods? Appreciate any help!

Answer №1

Let's assume that "origin" is the location where the pieces become accessible, in this case you can:

var origin = '[{"response": [{"id": 1}]}][{"response": [{"id": 2}]}]';
var pieces = JSON.parse('[' + origin.replace(/\]\[/g, '\],\[') + ']');
for (var x in pieces) {
  // proceed to work with pieces[x]...
}

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

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Use Volley to send a JSON with the format key:{key:value,key:[]}

I am a beginner in using Volley and parsing complex Json data. Here is an example of the Json data I am working with: "timings": { "summary": "Mon-Fri 9am-6pm", "detail": [ "Mon 9am-6pm", ...

When the mouse leaves, the gauge chart component's size will expand

I have encountered a problem while using the react-gauge-chart library in my react project. Within the project, I have integrated a popover component using material-ui and incorporated the gauge chart component from the library within the popover modal. T ...

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

Ways to fill in nested fields within a MongoDB schema

My schema consists of a summary structure: { sender: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true, }, summary: { type: String, }, sent: { type: Date, default: Date.n ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...

Jackson Password Serialization for Enhanced Security

Currently, I am utilizing Jackson to serialize objects for storage in MongoDB using Jongo. Within these objects is a password hash that needs to be stored in the database. Furthermore, there is a REST API set up to retrieve these objects. However, upon se ...

Retrieving information from a distant JSONP Entity

My challenge involves working with a JSONP object that generates 3 random numbers on a website. I have embedded the script below in an HTML document to access this JSONP object. <script> var url = 'http://dev.apalfrey.me/workspace/te2006-te2801 ...

Tips for modifying the appearance of an anchor <a> element within a table cell with jQuery

One issue I am facing involves changing the style of a specific element within a table cell using jQuery. The change needs to be based on the value in another cell. Below is the table structure: <table id="table"> ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

The Chevron icon is not pointing downwards even though it has already gone upwards

I want to toggle a chevron icon, but nothing seems to be happening. $("span:last").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up"); When I add this code below the slideToggle function without an if-else section, the icon changes to ...

Downloading multiple files on both iOS and Android devices

Is there a way to download assets (mp3/jpeg) in an Asynchronous manner? I have over 200 files in each case and the process is taking too long. Are there any techniques to speed up the download process on both iOS and Android? ...

Use jQuery to drag an element and display controls in a designated area

I am trying to develop a tool that allows me to drag an image from one section to another, and upon dropping it, the following actions should take place: 1 - The dragged image should revert back to its original position 2 - A set of controls should be add ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Utilizing Kendo for Dynamic HTML Element Connection

Currently, I am facing a situation where I have three HTML elements. The first is a textbox labeled shipToAddress, the second is another textbox called deliverToAddress, and finally, there is a checkbox named sameAsShipToAddress. In the background, there ...

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Aggregating data in MongoDB from a single collection

Just starting out with mongodb querying and I have a collection for messages in a chat app. The "members" array within each document represents the sender ID and receiver ID. Sender: 631012d34a181605afe342c1 Receiver: 62e8845c3e1d191dfdc1a244 "dat ...

Prompting the website to 'refresh' and return to the beginning of the page

My website's functionality is closely tied to the user's position on the page. Different features are triggered once specific distances are reached. I am seeking a way for users to automatically return to the top of the page upon page reload. Cu ...

The indicated processing instruction is incompatible with the provided payment source. PayPal's hosted fields for credit card payments do not support this specific processor

I'm currently working on integrating credit card payments with hosted fields into my checkout process. However, I keep encountering an UNPROCESSABLE_ENTITY error when making the confirm-payment-source request through the PayPal JS SDK. Here is the co ...