If I have this string:
{some_name:{other_name:"text",array:["first","second",3]}}
Is there a way to turn it into a usable object in JavaScript?
JSON.parse() can't do it because it expects the attributes to be surrounded in quotes like this
{"some_name":{"other_name":"text","array":["first","second"]}}
CodePudding user response:
Quick and dirty
eval('foo = {some_name:{other_name:"text",array:["first","second",3]}}');
console.log(foo);
foo
will be the usable object.
(but don't do it, eval is evil)
Cleaner way
You can transform it to a valid JSON and parse it.
const bar = '{some_name:{other_name:"text",array:["first","second",3]}}';
const foo = JSON.parse(bar.replace(/([^"])(\w ):/g, '$1"$2":'))
console.log(foo);
CodePudding user response:
I might guess you want a JSON object, you can use JSON.stringify like this:
const someObj = {some_name:{other_name:"text",array:["first","second",3]}};
const jsonResult = JSON.stringify(someObj);
and then you may call JSON.parse(jsonResult)