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
  • 24,996
  • 37
  • 121
  • 181

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
  • 376,160
  • 25
  • 347
  • 392
1

Try this:

var string = '{a: {b: 1}}';
eval('var obj='+string);
console.log(obj.a);
Grigory Volkov
  • 472
  • 6
  • 26