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

Following the upgrade of Angular, the webpack module source-map-loader is encountering an error: "this.getOptions is not a function"

Currently in the process of constructing my angular project using webpack alongside source-map-loader to extract source maps, like this: module.exports = { // ... module: { rules: [ { test: /\.js$/, enforce: "pre&quo ...

The search parameter is not functioning properly when making the API request

I'm currently learning about json and APIs. The dataset I am experimenting with () allows for search functionality by adding ?search=search_term to the URL (e.g., ). However, when attempting to use a different json dataset (), it returns an error: { ...

Is it possible to create a mapping for the jsonProperty of nested fields in an object?

In my project, I have created two classes named Car.java and Bus.java. Car.java private Property property; Bus.java private Property property; The Property.java class contains attributes for number and colour. ...

Steps to turn off fancybox for mobile and show the full image instead

In this scenario... I am seeking a way to deactivate fancybox functionality on mobile devices. I have already discovered one method to disable it... And now I want to directly show the large image in the a href="xxx_large.jpg" instead of using the img src= ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Using Vue and vue-multiselect to create interactive options based on the selected language

I'm currently developing a Vue website with multilingual support. The chosen language is stored in a Vuex store and accessed through the computed property lang, like so: lang(){ return this.$store.state.lang } I use this lang property in v-if cond ...

What is the best way to eliminate the "onclick" attribute from an HTML element using JavaScript?

Is there a way to make my code only execute the onlick function after a button is pressed? I want to prevent any action from happening before that. <!-- deactivate onclick function --> <div class="boardsection2" id="2_8_7" oncl ...

Create genuinely private methods within an ES6 Module/Class specifically for use in a nodejs-exclusive environment, ensuring that no data is exposed

Although there are no true private methods within ES6 classes, I stumbled upon something interesting while experimenting... While it's not possible to completely hide object properties, I attempted to follow OOP principles by dividing my classes into ...

A variant of setTimeout designed specifically for family members

I am currently working on a program that involves creating a "health" variable which decreases by random amounts at random intervals. This means that a player may encounter scenarios like the following: 5 seconds Lose 20 health 3 more seconds Lose 25 healt ...

Use .load() to set an image as background in the div

There is a block of code that is supposed to display images in a div with the class "img", but it isn't functioning correctly. Can you provide some guidance on how to fix this issue? <div class="other"><a href="/index1.html">Link1</a&g ...

Ignoring a nested object during Jackson JSON serialization when all its fields are null: How to do it?

Incorporating Jackson into my project, I have JSON schema objects structured as follows: @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Person { String name; Child child = new Child(); Sibling sibling = new Sibling(); public St ...

Steps to retrieve JSON data from a webpage

Exploring the realm of handling JSON data from a web API is new to me. I'm eager to delve into its intricacies and understand how it operates. Despite my online research, I am still unclear about the process. As far as I know, the general procedure i ...

Understanding the Execution of Asynchronous Code

I've been grappling with this problem for a while now, but I just can't seem to find the solution. That's why I'm reaching out for your expertise. Consider the example below: const async = require('async') var counter = 0 v ...

"Upon pressing the submit button in the router.post function, a null value appears

In my form, I am attempting to redirect the page to the home URL after clicking the submit button. However, using res.redirect('/home') is not achieving the desired result. I have also tried using console.log("testing");, but that is not working ...

Is it possible to utilize X-Y coordinates as repositories for values beyond just X-Y coordinates themselves?

I am in the process of creating a tile-based grid and I need to expand the X-Y coordinates to include additional values for determining characteristics of each tile, such as resources (for example, food, water, stone, lumber) within a game context. Conside ...

Internal Server Error in ASP.NET MVC 5 Controller when Returning JsonResult

What could be causing the 500 Internal server error I am experiencing? C# public JsonResult GetCategory(string id) { long eocategoryid = Convert.ToInt64(id); dbEntities db = new dbEntities(); ttCat ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

python: understanding the behavior of json.dumps with dictionaries

My goal is to modify the behavior of the dict when using json.dumps. I want to be able to order the keys, so I created a new class that inherits from dict and overrides some of its methods. import json class A(dict): def __iter__(self): for i ...

The Angular @HostListener beforeunload Event is a powerful way to handle

I've implemented the following code snippet in my main app.component.ts file within my Angular 17 project: @HostListener("window:beforeunload", ["$event"]) onTabClose($event: BeforeUnloadEvent) { $event.preventDefault(); ...

Can you explain the contrast between `/:foo*` and `/:foo(.*)` when used in express routes?

When using Express, it is possible to define endpoints with different paths: app.get('/:foo*', function(req, res) { ... }); app.get('/:foo(.*)', function(req, res) { ... }); Although these two paths may appear similar, what sets them ...