JavaScript code to transform a string into a JSON array

I utilized s3 select to extract specific data for display on my frontend. I converted an array of bytes to a buffer and then to a string as shown below:

let dataString = Buffer.concat(records).toString('utf8');

The resulting string looked like this:

 {"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
 {"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
 {"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
 {"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
 {"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
 {"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
 {"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
 {"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
 {"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
 {"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"} 
 {"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
 {"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
  

Now, I aim to convert them into a JSON array. The solution provided is as follows:

let dataArray = dataString.split('\n');
//remove white spaces and commas etc
dataArray = dataArray.filter(d=> d.length > 2);
//change string to json
dataArray = dataArray.map(d=> JSON.parse(d));

However, the issue arises when splitting them by new lines; it won't work if the JSON is compressed or contains new lines itself. How should I best handle this situation? I desire the output as presented below:

[{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"},
 {"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"},
 {"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"},
 {"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"},
 {"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"},
 {"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"},
 {"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"},
 {"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"},
 {"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"},
 {"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"},
 {"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"},
 {"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
]

Answer №1

@sumit please review this proposed solution.

let dataString=`{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
 {"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
 {"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
 {"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
 {"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
 {"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
 {"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
 {"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
 {"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
 {"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
 {"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
 {"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
 
 let dataArray = dataString.match(/{(?:[^{}]*|(R))*}/g);
 dataArray = dataArray.map(d=> JSON.parse(d));
 console.log(dataArray);

Answer №2

Avoid concatenating objects into a string if possible. If you have no other choice, consider using this method:

const initialString = `{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
 {"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
 {"id":"3","o...

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

Retrieve the properties from within a closure function in a functional component

I have developed a simple React application using create-react-app. The app consists of a single component that takes in a value and an onClick callback. When the callback is triggered, the value increments. import React, { useState } from 'react&apos ...

Sending FormData from React.js to an Express.js backend results in loss of data

I encountered a problem while developing a book library management CRUD system using React v18. The issue arises when attempting to add data to my MongoDB Atlas database. Whenever I pass the formData to axios.post through Redux, the req.body on the backend ...

Customize the formatting of linked locale messages in Vue's internationalization (i18n) feature using parameters

Is there a way to link locale messages in vue-i18n with a parameter? { "next": "Next step {step+1}: @:steps[{step}]", "steps": [ "Welcome", // 0 "Briefing", // 1 "Finish" // 2 ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

What is the process for retrieving my dates from local storage and displaying them without the time?

Having an event form, I collect information and store it in local storage without using an API. However, I face a challenge when extracting the startdate and enddate out of localstorage and formatting them as dd-mm-yyyy instead of yyyy-mm-ddT00:00:00.000Z. ...

Tips for successfully passing multiple properties to a function in React

<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => { deleteHomework(value.name, value.class); }} /> I'm looking to modify the function deleteHomework so that it can receive two properties instead of just one. In add ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

Total value of JSON objects in MySQL集体に集計

I've recently created a new table with details stored as JSON data type. While attempting to retrieve the total sum of all records, I was able to access each value individually but struggled with obtaining the sum using group by options. CREATE TABL ...

When using AngularJS and PHP together, I encountered an error that stated "

My POST http request is encountering an error with the message Undefined property: stdClass::$number and Undefined property: stdClass::$message. Below are the codes I've been using: smsController.js angular .module('smsApp') .contr ...

What are the steps to add code into the Monaco Editor using Playwright?

As I explore the world of Playwright, I am faced with a challenge regarding testing a feature that involves a monaco editor. Unfortunately, my search in Playwright documentation and forums did not yield any relevant information. Here is the test scenario ...

Using ng-repeat within another ng-repeat allows elements to be displayed as siblings

My goal is to create a structured list using angularjs: Parent 1 Group1 Child1 Child2 Child3 Child4 Group2 Child1 Child2 Parent 2 Group1 Child1 Child2 Group2 Child1 I have data organized in a similar format like this. $scope.parents = [{ name:&apos ...

Playing with background hues

Can anyone help me with this issue? I've been attempting to change the background color using jQuery upon document load, but it doesn't seem to be working. Any thoughts on what I might be doing wrong? http://jsfiddle.net/KczZd/2/ HTML: <d ...

Transferring SQL-generated JSON object from PHP to JavaScript

Seeking assistance with passing a JSON object from PHP to Javascript. The object is populated from an SQL Database using the following PHP code snippet. <?php $conn = mysql_connect("localhost","root",""); if(! $conn ) { die('C ...

Encountering an error stating that a JSON array cannot be transformed into a JSON object

I need to send a JSON array to a web server. The JSON array is created from an array list and there is a helper class that sends the JSON object to the server. My goal is to convert the JSON array to a JSON object. I attempted the following: public clas ...

Chrome not triggering the fullscreenchange event

I've been attempting to track when the browser goes into fullscreen mode. Everywhere I look, this blog is mentioned as the go-to resource on the fullscreen API. According to this SO answer, it should work. Fullscreen API: Which events are fired? B ...

Could there be a glitch in the angular code related to cleanliness

It seems like there might be an issue with Angular rather than my code. I'm trying to create a dynamic form using ng-repeat and encountering a problem where the form scope shows that pristine is true, even when it's not. Plunker can handle form p ...

Stopping multiple queries in Node.js can be achieved by using proper error handling

Upon verifying the existence of the name, the program continues to the subsequent query and proceeds with inserting data, which results in an error due to multiple responses being sent. How can I modify it to halt execution after checking if (results.row ...

transition from jQuery to Zepto

I have been utilizing multiple jQuery plugins in my codebase... Recently, I decided to switch over to Zepto, but encountered an issue Uncaught TypeError: Object function (a,b){return A.init(a,b)} has no method 'data' when checking the console ...

Unable to locate video identifier on ytdl

Lately, I have been working on developing a music bot for Discord. I have successfully managed to make it join and leave voice channels flawlessly, but playing music has proven to be quite challenging. For some reason, the play and playStream functions do ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...