The process of converting a string containing a list of object properties into separate objects using JavaScript

I am trying to transform the following string into actual objects. It seems that JSON.parse is not functioning as expected because all the properties are grouped together in a single string instead of being separate. This text string is retrieved from an API request.

Transform

var s ="{prop1:\"value\", prop2:\"value2\", prop3:\"value3\"}";

to

s = {prop1: 'value1', prop2: 'value2', prop3: 'value3'};

Answer №1

let obj ="{name:\"John\", age:\"30\", city:\"New York\"}"

console.log(parseStringToObject(obj))

function parseStringToObject (str){
  let resultObj = {}
  str.replaceAll(' ','').replaceAll('"','').replaceAll('{','').replaceAll('}','').split(',').map(x=>{
    const temp = x.split(':')
    resultObj[temp[0]] = temp[1]
  })
  return resultObj
}

Or in a simpler way:

console.log(JSON.parse(obj.replaceAll("{",'{"').replaceAll(', ',', "').replaceAll(':','":')))

Answer №2

Why not consider using eval() method?

eval('let obj =' + "{key1:\"value1\", key2:\"value2\", key3:\"value3\"}");

I understand that eval may not be the most optimal choice.

However, if you prefer not to break down the string, it could be a possible solution...

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

What is the method for altering the color of specific columns?

I am currently testing out my Amchart with this example. Check out the working demo on code pen My goal is to modify the color of the first four columns. While I am aware that colors can be changed by specifying them in the JSON file as a property calle ...

Retrieving all the information stored in the tables

I'm struggling with retrieving the content of my table cells. Some cells contain a hyphen (-) and if they do, I want to center the text. I'm facing difficulties with my jQuery code, particularly the if statement which always evaluates to false. ...

Retrieving a sequence of bytes from a JSON object

In my possession is a JSON structured as follows: [{"fingerprint":"[79,0,0,0,18,0,0,0,18,0,0,0,19,0,0,0,23,0,0,0,40,0,0,0,42,0,0,0,63,0,0,0,68,0,0,0,71,0,....]"}] I've been attempting to extract the byte array from it using this code snippet: JSONF ...

Saving a JSONObject to a file

Utilizing the Play framework, I am dealing with a JSONObject that has a specific structure as displayed below (printed in the console) { "rows_map":{ "220":["mahesh", "outfit:bmtech,app:salesreport,uuname,ffname,llname", ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

The jQuery functions properly offline, but fails to load when connected to the

I am encountering an issue with the following script: <script type="text/javascript"> $.getJSON("http://api.twitter.com/1/statuses/user_timeline/koawatea.json?count=1&include_rts=1&callback=?", function(data) { $("#headertweet") ...

Dealing with Grails command objects and encountering a 404 error due to spaces within JSON data sent

Recently, I came into possession of a controller. Interestingly, when a post request is sent with a precisely formatted JSON document, everything runs smoothly. However, the situation changes drastically when the JSON includes a space in one of its field ...

The for...of loop cannot be used with the .for property since it is not iterable. (Is

let arr = [{ category: 'music', views: 20 }, { category: 'abc', views: 32 }, { category: 'bob', views: 20 } ] for (const [key, value] of arr) { console.log(key, value) } console.log(Array ...

What is the best approach for running a database query using the value selected from a form dropdown?

Currently, my application server is ColdFusion and I am using SQL Server for the database. Within a select form element on my webpage, users can choose from a list of vehicles such as Volvo S60, BMW M6, and VW Jetta. Once a user selects a vehicle, I need ...

How to assign attributes to multiple menu items in WordPress without using JavaScript

I'm currently working on adding attributes to each item in my WordPress navbar. Here is what I have at the moment: <ul id="menu-nav-bar" class="menu"> <li><a href="#text">text</a></li> <li><a href="#car ...

Design your very own personalized Show Layout component

Currently, I'm in the process of creating a unique layout component to enhance the design of my Show page. I've encountered some inconsistencies with functionality, and my solution involves utilizing the Material-UI <Grid> component. While ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

How come my links aren't initiating jQuery click events?

Today, I decided to experiment with jQuery and encountered an issue. On my webpage, there are multiple links displayed in the format shown below: <a class="a_link" id="a_id<#>" href="#">Click me</a> The value <#> is a number gener ...

Using table.column as a function in jQuery datatabbe is not supported

When using jquery datatable, I encountered an error stating "table.column is not a function." <script> $(document).ready(function() { var table = $('#lsotable').dataTable(); $("#lsotable thead th").each( function ( i ) { ...

Unable to access the store from the Redux library within a React application

I decided to test out the Redux example from the official React-Redux website, which can be found HERE, using the following JavaScript code: // index.js import React from 'react' import ReactDOM from 'react-dom' import TodoApp from &ap ...

Utilize the native HTML attribute to capture the mouse wheel event

I'm interested in utilizing the mousewheel event in my project, but all the information I've found online relies on addEventListener(). I want to detect it using native HTML and CSS. In simpler terms, I'm hoping for something along the lines ...

Transmitting multiple file attachments to a PHP file through AJAX

In my form, I have the following HTML code: <input type="file" id="attachments" name="attachments" multiple> I've already implemented a JavaScript function that handles form submission using AJAX, but it doesn't handle uploaded files. Wi ...

Is it possible to dynamically incorporate directives within an AngularJS application?

I'm attempting to utilize several custom directives within the Ionic framework. The dynamic structure is like <mydir-{{type}}, where {{type}} will be determined by services and scope variables, with possible values such as radio, checkbox, select, ...

The V-model is failing to bind properly as anticipated

One feature of my application involves a table that displays a list of products. Each product row in the table has an input field where users can enter the quantity they want to purchase. The total cost for each product is dynamically calculated by multipl ...