2

Given a STRING (not object) that represents JS object.

'{a: {b: 1}}' (not object but string)

Is there some simple general way to convert it to JSON {"a": {"b": 1}}? Maybe parse and covert, as JSON.parse is not applicable.

WHITECOLOR
  • 22,508
  • 35
  • 117
  • 177

2 Answers2

2

If you have no other content than this, you could take eval with parentheses around to prevent that it is interpreted as a block statement with labels.

Maybe worth a look:

var string = '{a: {b: 1}}',
    object = eval(`(${string})`);

console.log(object);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
1

Try this:

var string = '{a: {b: 1}}';
eval('var obj='+string);
console.log(obj.a);
Grigory Volkov
  • 482
  • 4
  • 22