简体   繁体   中英

How to parse a string into javascript object?

I have a javascript object defined inside a string variable:

const str = "{a:1}";

I wonder what is the best way to convert it to a javascript object. I have searched a lot but all I found is to use JSON.parse or JSON.stringify to convert the string. But the tricky part in this string is that it is not a JSON object. The a is not quoted. I have tried below approach but it doesn't parse it to a object:

JSON.parse(JSON.stringify(str))

I know I can parse the string manually but I am looking for a more generic solution which support parsing all possible javascript object string.

var obj = eval(str);

Just be aware that using eval can have performance and security impacts.

If you don't control the content of str, ie it is a user input or it comes from a server you don't trust, the are risks.

Also, the JavaScript runtimes optimizes your code at runtime, but often disable many optimizations when engineering an eval .

Try to wrap the evaluation statement in a self invoked function that receive the variable passed to the eval :

(function(s) {
    return eval(s);
}(str));

It ensures the creation of a closure to isolate the eval , mitigating it's potential impacts.

And last, don't take anything I've just said as an absolute truth: benchmark your code with and without the eval, just to be sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM