Navigating through concatenated JSON strings in a web browser: A step-by-step guide

I am currently using Socket.IO to transmit data to the browser. The information being sent is a continuous stream of JSON objects, which upon arrival at the browser, transforms into a single large JSON string. However, the issue I am encountering is that this JSON string cannot be parsed by JSON.parse() due to its unconventional format.

Since the structure of the data can vary greatly, utilizing RegEx may not provide a viable solution. Additionally, it is important to note that the current setup is only temporary. Eventually, the server will preprocess the JSON stream before sending it to the browser, eliminating the need for a real-time stream. Therefore, I prefer to maintain the existing AJAX/Socket.IO configuration rather than switching to a JSON stream parser like OboeJS.

Is there a workaround to effectively parse this concatenated JSON string?

To clarify, the JSON will have the following structure:

{"a":"A"}{"b":"B"}{"c":"C"}

My objective is to parse it in a manner that allows me to access the individual elements as follows:

console.log(Object.a) //A
console.log(Object.b) //B
console.log(Object.c) //C

Answer №1

If you're facing a situation like yours, consider employing Array.prototype.reduce to combine all JSON objects into one:

var unstructuredJson = '{"a":"A"}{"b":"B"}{"c":"C"}';
var jsonArray = "[" + unstructuredJson.split("}{").join("},{") + "]";
var objectArray = JSON.parse(jsonArray);

var result = objectArray.reduce(function(result, item) {
  Object.keys(item).forEach(function(propertyName) {
    result[propertyName] = item[propertyName];
  });

  return result;
}, {});

document.body.textContent = JSON.stringify(result);

The original poster mentioned in a comment:

[...] Each JSON might have nested data like {{}{}}{}{}{}

In such cases, the approach above may not work correctly.

A suggestion would be to use a delimiter when concatenating these JSON objects. This way, it will be easier to separate parent objects and only require changing split("}{") with the actual separator.

I recommend choosing a character that wouldn't normally appear within any property value. You can refer to this Wikipedia article on Control characters for ideas: Control character

Answer №2

In the case where each substring is valid JSON but when concatenated it doesn't form a valid JSON, a solution is to turn the string into a valid array literal and utilize JSON.parse. This way you can then process each object using Array methods like forEach:

var s = '{"a":"A"}{"b":"B"}{"c":"C"}';
var obj = JSON.parse('[' + s.replace(/}{/g,'},{') + ']').forEach(function (obj) {
  document.write(JSON.stringify(obj) + '<br>');
});

Alternatively, if you prefer to have it as a single object:

var s = '{"a":"A"}{"b":"B"}{"c":"C"}';
var obj = JSON.parse(s.replace(/}{/g,','));

document.write(JSON.stringify(obj));

Answer №3

To parse concatenated JSON objects, you can utilize the JsonParser as shown below:

    ObjectMapper objectMapper = new ObjectMapper();
    JsonFactory jsonFactory = new JsonFactory(objectMapper);

    JsonParser jsonParser = jsonFactory.createParser(jsonString);
    List<YourObject> yourObjectList = new ArrayList<>();

    Iterator<YourObject> iterator = jsonParser.readValuesAs(YourObject.class);
    while(iterator.hasNext()) {
        YourObject yourObject = iterator.next();
        yourObjectList.add(yourObject);
    }

Answer №4

Slice the extensive string {x:'X'}{y:'Y'}{z:'Z'} and analyze each part separately

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

Dialog in Angular Material refuses to close even after calling the dialog.close() function

I've been struggling with this issue for a while, hoping someone can assist. In my Angular project, I have a login component with a dialog that opens a new popup window. Upon successful login, this window closes and triggers the following function: l ...

What is the best way to initially conceal content and then reveal it only after an ajax call is made?

Currently, I have a situation where content is revealed after the callback function of a .js library (typed.js) executes. Here is the script I am using: Javascript $(function(){ $("#logo-black").typed({ strings: ["Nothing^450&Co^250.^500" ...

Struggling with validating forms with JavaScript

I'm having trouble with the following JavaScript code: <script type="text/javascript"> function checkDetails(search) { var search = documment.getElementById('query'); if(search.value ==''||search.val ...

Show a distinct row from an API using React

I am attempting to create a map function to display all the items from the API Screenshot of code showing the items Here is the console log displaying the fetched items from the API I encountered an error with the map function not working. Any solutions ...

Looping through each entity in Symfony allows for the conversion of entities to JSON format

In my project, I have implemented a small REST API where I utilize JSON for the return data. The backend framework I am using is Symfony and the frontend utilizes AngularJS. Currently, I convert my entity to JSON by iterating through the results and popul ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

Issue with attaching dynamic events is not functioning as expected

var smartActionsId = ['smartActions1','smartActions5','smartActions10']; for (let i in smartActionsId) { console.log("smartActionsId ="+smartActionsId[i]); $('#' + smartActionsId[i] + ' select').c ...

Building on the foundation of Web API 2.0: Using JavaScriptConverter for Tailored Date Formats

I want to standardize every DateTime object to follow the format "yyyy-MM-dd". Previously, I achieved this by adding the following code snippet to WebApiConfig.cs using JSON.Net: config.Formatters.JsonFormatter.SerializerSettings.Converters.Add( ...

Issue with rendering an object's property using EJS

Trying to include the author's username in reviews within an ejs template for my app. The following code snippet: <%= review.author %> is functioning correctly and displays: { _id: 5eff6793e7f26811e848ceb1, username: 'mike', __v: 0 ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

Tips for adjusting the position of an infowindow in ArcGIS

I have implemented the use of infowindow in arcgis to display certain information. https://i.sstatic.net/Dnpas.jpg Currently, the infowindow is appearing directly over my icon. Is there a way to adjust its position if it covers the icon? ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...

Dropzone user interface package experiencing issues with displaying image previews

I recently installed the dropzone-ui package and noticed that while file items load and file icon previews show up when I drop files on the dropzone, image previews are not displaying. Could it be an issue with my implementation? Here's a snippet of ...

Is it possible to automatically close navigation dropdowns when the screen size changes?

I am using a bootstrap 4 navbar with dropdowns that open with CSS animation/fade-in on desktop, and a separate toggle button for mobile. Everything works fine, but when I open the dropdowns on mobile and then resize the window screen, they remain open whic ...

Remove entire objects from a JSON structure if they do not contain any key-value pairs

I want to filter out objects from a JSON file that do not contain specific keys such as: "transaction_date", "asset_description", "asset_type", "type", and "amount". Here is an excerpt of the JSON file: { "first_name": { "0": "Thomas", ...

Unraveling exceptions in Node.js akin to handling them in Java

I'm seeking to develop a node application and I need guidance on exception handling. In Java, we utilize the exception class for this purpose. How can I achieve something similar in node? Are there any libraries available specifically for handling exc ...

Stylist in Visual Studio Code for React applications

Whenever I try to save or format my React code using Ctrl + Shift + F, the formatting of the code below seems unusual. Is there a way to fix this issue? The original code is as follows: import logo from './logo.svg'; import './App.css&apos ...

When utilizing Md-select in Protractor, how can the dropdown list be accessed?

I am having trouble locating the option from the dropdown menu that I need to select. Despite trying various methods, I have not been successful. <md-select ng-model="card.type" name="type" aria-label="Select card type" ng-change="$ctrl.onCardSelecti ...

Is it possible to alter the css twice through the action of clicking on two individual buttons

One feature I have in my interface allows users to click on the edit button to bring up borders and change the background color of other divs. Once the edit button is pressed, it is replaced by cancel and save buttons. The goal is for the borders and backg ...