Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript string to object

How to apply string object value to a variable Ex.

var str='{a:"www"}' 

Now how to set

var obj={a:"www"} 

I try eval() but not working

like image 509
Ankit_Shah55 Avatar asked Dec 05 '12 07:12

Ankit_Shah55


People also ask

Can I convert string to object JavaScript?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

Which method converts a string to a JavaScript object?

Javascript has provided JSON. parse() method to convert a JSON into an object.

Can we convert string to JSON in JavaScript?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.


1 Answers

eval should work, and it's actually a MDN solution, not to mention that your string is not a valid JSON, so eval is your only option (if you don't want to include a library for that).

var str='{a:"www"}'; var obj=eval("("+str+")"); console.log(obj); 

Quick test in Chrome Dev Tool:

eval("("+'{a:"www"}'+")") Object     a: "www"     __proto__: Object 

Just remember to wrap your string in parenthesis and assign it outside eval and it'll be (relatively) safe.

like image 82
Passerby Avatar answered Sep 22 '22 00:09

Passerby