0

Is there an easy way to parse an object literal as a string into a new object?

I'm looking to turn a string like the following:

'{ name: "A", list: [] }'

Into an object like:

{ name: 'A', list: [] }

Note:

I'm not looking for JSON.parse() as it accepts json strings and not object literal strings. I was hoping that eval would work but unfortunately it does not.

1

2 Answers 2

3

eval does indeed work, with one tweak: the problem is that the standalone line

{ name: 'A', list: [] }

gets parsed as the interpreter as the beginning of a block, rather than as the start of an object literal. So, just like arrow functions which implicitly return objects need to have parentheses surrounding the objects:

arr.map(item => ({ item }))

you need to put parentheses around the input string, so that the content inside (that is, the object, which starts with {) is parsed properly as an expression:

const input = '{ name: "A", list: [] }';
const obj = eval('(' + input + ')');
console.log(obj);

Of course, as with all cases when eval is involved, you should be very sure that the input is trustworthy first.

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

Comments

1

While I would never do this IRL, you could perhaps try this:

var myObjLiteralString = '{ name: "A", list: [] }';

var myObj;
eval('myObj = ' + myObjLiteralString);

console.log(myObj);

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.