1

How can I convert the string...

"{ name: 'John' }"

...to an actual JavaScript object literal that will allow me to access the data using its keys (I.e. varname["name"] == "John")? I can't use JSON.parse(), since the string is invalid JSON.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
BeachRunnerFred
  • 18,070
  • 35
  • 139
  • 238
  • I'd prefer avoiding `eval` and make the source produce proper JSON. – Thilo Oct 03 '14 at 01:25
  • Starting with JSON is best, as @Thilo suggested. Parsing strings with `eval(…)`, `require(…)`, `new Function(…)`, `document.createElement('script')`, etc, will cause the code in the string to be executed, which is probably dangerous if the string comes from outside your program. If your only source of data is JS object literals, the best way may be to use an AST parser such as [Esprima](https://esprima.org/) as suggested [here](https://stackoverflow.com/a/56649864/277303). – Quinn Comendant Jun 30 '20 at 01:32

3 Answers3

2

Example with new Function

var str = "{ name: 'John' }";
var fnc = new Function( "return " + str );
var obj = fnc();
console.log(obj.name);
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You could use eval().

var str = "{ name: 'John' }";
var obj = eval("(" + str + ")");
svanryckeghem
  • 913
  • 6
  • 6
1

From the previous question

s="{ name: 'John'}";
eval('x='+s);
Leo
  • 4,136
  • 6
  • 48
  • 72