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.

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Right thanks, forgot about eval at all, anyway it is quite applicable in my case.
1

Try this:

var string = '{a: {b: 1}}';
eval('var obj='+string);
console.log(obj.a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.