Change the server's response into a usable object using JavaScript

When receiving a response from the server, it appears in this format:

{"value1":1,"value2":45,"value3":"x"} 
{"value1":1,"value2":45,"value3":"x"} 
{"value1":1,"value2":45,"value3":"x"} 

The response is in text form.

I'm having trouble parsing the JSON due to an error saying "Unexpected token {". Can someone assist me in converting this into a valid object?

UPDATE 1

The output after using the following code:

const arr = `[${res.replaceAll('\n', ',')}]`

Is:

[{"value1":1,"value2":45,"value3":"x"}, 
{"value1":1,"value2":45,"value3":"x"}, 
{"value1":1,"value2":45,"value3":"x"}]

It seems there is an issue with the last comma when copying the data manually. This error does not occur in that case.

UPDATE 2

Furthermore, the server response contained invisible empty lines that I initially overlooked. Using trim() function fixed this issue.

Answer №1

To resolve an issue, consider addressing it first on the server side before attempting to fix it on the client side as a last resort.

The text you provided appears to be:

{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}

It contains whitespace at the end. You can remove all spaces around it, replace line breaks with separators, and enclose everything in square brackets. Then, parse it as JSON:

JSON.parse(`[${res.trim().replaceAll('\n', ',')}]`)

This will create an array of objects that you can manipulate as needed.

For example:

const res = `{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}
{"value1":1,"value2":45,"value3":"x"}`;

const arr = JSON.parse(`[${res.trim().replaceAll('\n', ',')}]`);
console.log(arr);
console.log(arr[1].value2);

Answer №2

UPDATE: My interpretation of the question was off, so here is a revised response:

const data = `{"value1":1,"value2":45,"value3":"x"}\n{"value1":1,"value2":45,"value3":"x"}\n{"value1":1,"value2":45,"value3":"x"}`;

const dataArray = data.split("\n");

let finalOutputArray = [];

dataArray.forEach(item => {
    
    let inputObject = JSON.parse(item);

    let outputValueArray = [];

    // iterate through all values in the object
    for (const key in inputObject) {

        // append the new value to the array
        outputValueArray.push(inputObject[key]);
    }
    
    finalOutputArray.push(outputValueArray);
});

console.log(finalOutputArray); // should display "[ [1, 2, 3, ...], [1, 2, 3, ...], ...]"

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

Updating a specific property within an array of objects by identifying its unique id and storing it in a separate array of objects

Struggling to merge these two arrays? Look no further! By comparing the parent id to child parentsId, you can effortlessly push the second array as an extra property to its parent. Save yourself hours of frustration and achieve your desired output with a l ...

determining the preference between setTimeout and setImmediate

After reading the documentation on the node, it mentions: setImmediate(callback, [arg], [...]) This function is supposed to execute callback immediately after I/O events callbacks and before setTimeout and setInterval However, in practice, I noticed tha ...

Utilizing Promise.all with map and async functions in Node.js ensures non-blocking behavior during function calls

After developing a small module to communicate with Zookeeper and retrieve a list of service endpoints, everything seems to be working smoothly except for the part where the list of endpoints is returned. Within the module, there is a function that is supp ...

The OrhographicCamera is having difficulties capturing the entire scene in its render

Recently, I have been working on rendering a scene using three.js and WebGL in an isomorphic manner. In my research, I came across suggestions to use the OrthographicCamera for this purpose. However, upon implementing it, I noticed some strange outcomes. A ...

What is the best way to generate a ul-li structure using JSON input and jQuery?

There is a JSON variable present: var links=[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home","children":[{"text":"home2","href":"home2.com","icon":"fas fa-chart-bar","target":"_self","title":"home2","category ...

how can you add an object to an array in react native without altering the properties of the array

In my attempt to contract an array for use in 'react-native-searchable-dropdown', I have encountered an issue while trying to push objects into the array. Here is the code snippet that I am struggling with: let clone=[]; obj={{id:8,name:'Yyf ...

How can I display input only when a checkbox is selected? React with Next.js

I'm trying to figure out how to handle this task, but I'm a bit confused on the approach. I would like to display the promo code field only when the checkbox (I have a promo code) is checked. Additionally, it would be ideal to reveal this field ...

Validating the body in Node.js for POST and PUT requests

When working in a production setting, what is considered the standard for POST / PUT body validation? I typically approach it like this: const isValid = (req.body.foo && /[a-z0-9]*/i.test(req.body.foo)) This method involves checking that the var ...

Using V-bind to assign multiple classes has never been easier

Is there a way to assign one of two classes to an element based on three possible input variables in my Vue.js code? <input type='text' class='inputwordtext' v-bind:class="{(wordupload.firstchoice.selected == 'Zinnenlijst' ...

Is it necessary to register a client script again after a post-back event?

Is it necessary to re-register a client-script block on all post-backs if it is added on the first page load like this? if (this.Page.IsPostBack==false) { if (this.Page.ClientScript .IsClientScriptI ...

Having trouble loading a chart with amcharts after sending an ajax request

I have integrated amcharts to create a pie chart. When I click a button, an AJAX request is triggered to fetch data from MySQL in JSON format. After receiving the JSON array, I pass the data to amcharts but the chart doesn't display. Oddly, if I redi ...

Best method for creating HTML elements with jQuery

I've come across various styles and methods for creating elements in jQuery, each with its own unique approach. I am interested in discovering the most effective way to construct elements and whether a specific method stands out as superior for any pa ...

Form duplicates messages sent

I have made some adjustments to a free form, and it seems to be functioning properly. However, I have encountered an issue where the email is being sent twice and the message is written twice after completion. I attempted to replace the button and input ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

Designing Object-Oriented JavaScript

Currently, I am in the process of developing a sophisticated JavaScript application. Utilizing an object-oriented design approach, I have organized my code into various files to enhance maintainability. In order to create my application, what is the best ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...

Best Practices for Handling an Abundance of Data in React or Java

I am facing a challenge with my project setup, where I have the front end in ReactJS and the backend API in Spring Boot. The task at hand is to display a drop down list filled with records retrieved from the API. Here's the scenario: I receive a list ...

The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of ...

Adding jQuery namespace to AngularJS

I'm facing a bit of an issue here. I've implemented RequireJS to manage my modules and dependencies. To prevent cluttering the global namespace, I've set up the following configuration to avoid declaring $ or jQuery globally: require.confi ...