Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a string like
params="domain:Abcd-E-Group,domaintype:com,Submit1:Search"


Now i want to convert this to


obj={domain:"Abcd-E-Group",domaintype:"com",Submit1:"Search"}

What I have tried:

I have tried JSON.parse(params); and eval(params);

Both are not working for me.
Posted
Updated 11-Feb-23 14:09pm

For the JSON.parse() to work, the string params must be in correct JSON syntax[^]
Try this:
C#
var params = '[{"domain":"Abcd-E-Group","domaintype":"com","Submit1":"Search"}]';
obj = JSON.parse(params);
alert(obj[0].domain);

Read more: JSON Example - Object From String[^]
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 27-May-16 1:23am    
5
In addition to the Peter's Solution,

If the string is in the format which you have provided, then you shall try this to convert it to a json object.

JavaScript
var params = "domain:Abcd-E-Group,domaintype:com,Submit1:Search";

          var jsonStrig = '[{';
          var items = params.split(',');
          for (var i = 0; i < items.length; i++) {
              var current = items[i].split(':');
              jsonStrig += '"' + current[0] + '":"' + current[1] + '",';
          }
          jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
          jsonStrig += '}]';
          alert(jsonStrig); //[{"domain":"Abcd-E-Group","domaintype":"com","Submit1":"Search"}]
          var obj = JSON.parse(jsonStrig);
          alert(obj[0].domain);
 
Share this answer
 
Comments
Prateek Dalbehera 28-May-16 12:30pm    
Perfect and exact solution, right from beginning to end. Simply, first do a JSON.stringify() to convert a string to JSON string format and then parse using JSON.parse() to convert a json string to object.
Karthik_Mahalingam 28-May-16 12:38pm    
Thanks Prateek.
I got my Solution with this.

obj={};
var params="domain:Abcd-E-Group,domaintype:com,Submit1:Search";

var KeyVal = params.split(",");

var i;
for (i in KeyVal) {
KeyVal[i] = KeyVal[i].split(":");
obj[KeyVal[i][0]]=KeyVal[i][1];
}
 
Share this answer
 
let person='{firstName:"John", lastName:"Doe", id: 55, fullName:function(){return this.firstName+" "+this.lastName} }';

function strToObj(e){ var obj=new Function("return" +e); return obj() };

person=strToObj(person);

console.log(person.fullName())
 
Share this answer
 
v7

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900