Converting a stringified array of objects into an actual array of objects using Javascript

After receiving a HTTP response, I am faced with the challenge of working with the following variable:

let data = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'

Although there are more objects with additional properties, this snippet provides a glimpse of the data structure.

Upon attempting to use JSON.parse(data), an error is thrown:

[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n

What approach should I take in order to successfully parse this string into an array of JavaScript objects?

Answer №1

This JSON is invalid. To make it valid, you must enclose the keys in quotes ("name").

[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]

The mistake is due to the parser encountering an 'n' instead of a closing quote mark.

Answer №2

Due to the invalid JSON format (missing quotes around property keys), parsing the string using JSON.parse is not possible. If you have control over the response, consider returning:

[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]


See it in Action:

var data = '[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]' 

console.log(JSON.parse(data))
.as-console-wrapper { min-height: 100%; }

Answer №3

Due to the strict input format, the parsing process can be easily carried out.

function removeEdges(inputString) { return inputString.substring(1, inputString.length - 1); }
var keyValuePairs = removeEdges(output).split(', ');
var listOfObjects = keyValuePairs.map(function(pair) { 
    var separatedPair = removeEdges(pair).split(': ');
    var object = {};
    object[separatedPair[0]] = removeEdges(separatedPair[1]); 
    return object;
});

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

ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated! function onlyOne(checkbox) { var checkboxes = document.getElement ...

Angular pop-up message not displaying title or content

I have integrated the toaster directive into my AngularJS web project. Following the documentation, I have declared the container on my view as shown below. <toaster-container toaster-options="{'time-out': 3000, 'close-button':true ...

Exploring a new approach to organizing data with LocalStorage and AngularJS

I developed an application that utilizes LocalStorage to store data. The issue I encountered was storing a large number of objects under a single key, causing the DOM to become blocked. This is due to the necessity of parsing and stringifying the JSON dat ...

Switch the background color alternately from red to green every second

Need help with a webpage that changes the background color every second using JavaScript. The issue lies in figuring out how to correctly change the variable within the function. Here's an example of the code: <!DOCTYPE html> <html> ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

Performing Jquery functions on several elements at once

Looking at the code snippet below, there are two buttons and an input in each container. The input calculates and adds up the number of clicks on the 2 buttons within the same container. However, it currently only works for the first container. How can thi ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

User-generated JSON Object with Date Information

I have created an API using Node.js/Express that receives input from a form including a date option in the request body. Currently, I am sending dates in the format YYYY-mm-dd, and I have also attempted using dd/mm/YYYY. However, when testing in Postman, ...

What are the specific extensions for email validation?

code for the form: <form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" > <p class="email"> <label for="budget">Expected Budget ...

Utilize the to_json function in Postgres to convert multiple columns into JSON format

Assume I have the following table structure in Postgres: CREATE TABLE users (id text, email text, phone_number text); If, for any reason, I wish to retrieve the email and phone number as JSON data: SELECT to_json(users.email, users.phone_number) AS user ...

How do you eliminate row highlighting on the <TableRow> component within Material-UI's <Table> using ReactJS?

I am facing an issue with a table and row highlighting in my code. Even after clicking on a row, it remains highlighted. I attempted to use the <TableRow disableTouchRipple={true}> but it didn't work as expected. What can I do to remove the high ...

`Increase Your Javascript Heap Memory Allocation in Next.js`

We are facing a challenge with the development environment for our Next.js application. Issue The Javascript heap memory is consistently depleting. Here are the specific error logs: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out ...

The image code is not recognizing the image source

In my attempt to dynamically set the image source in an HTML element after creating it with JavaScript, I have made some interesting observations through testing and alert messages: When providing the image src as a fixed filepath during the creation o ...

Is it possible to create a Vue JSX component inside a Single File Component using the <script setup> syntax and then incorporate it into the template of the S

I am impressed by how easily you can create small components within the main component file in React. Is it possible to do something similar with Vue 3 composition API? For example: Component.vue <script setup> const SmallComponent = <div> ...

Unable to interpret JSON input when calling Bing Distance Matrix API from PHP

While I have successfully made a call to the Bing distance matrix service using Postman, I am encountering issues when trying various cURL methods and Unirest in my application where I pull data from MySQL. The error message I receive is: JSON input cou ...

Using Jquery to drag and drop items into a specific target zone

Check out my Jquery code: $(".list").draggable({helper: 'clone', cursor: 'hand'}); $(".drop1").droppable({ accept: '.list', hoverClass: 'dropareahover', drop: function(ev, ui){ var targetId = $(this) ...

"Why does the form.submit() function fail in IE9 when the form is in an iframe and the user is coming from Gmail

I have recently developed a function within my CodeIgniter framework that allows me to send emails with a backlink to my site. The link directs users to a page on my website that includes an iframe. Within this iframe, I have implemented a file input form ...

A step-by-step guide on incorporating the C3 Gauge Chart into an Angular 5 application

I have been attempting to incorporate the C3 Gauge Chart from this link into a new Angular 5 application. Below is my code within chart.component.ts : import { Component, OnInit, AfterViewInit } from '@angular/core'; import * as c3 from &apos ...

Enhancing link functionality with jQuery on a dynamically generated server page

I am facing an issue with my navigation menu that includes dropdowns. On desktop, the parent items need to be clickable as well, which is not a problem. However, for it to be responsive on mobile devices, I need to account for the lack of hover capability. ...

Sorting through JSON data obtained through YQL

Hello coding enthusiasts, After facing challenges with CORS in an AJAX project, I discovered a workaround using YQL to successfully retrieve JSON data. Now, I'm looking for ways to access and organize this data according to my preferences. Below is t ...