简体   繁体   English

如何将字符串解析为javascript对象?

[英]How to parse a string into javascript object?

I have a javascript object defined inside a string variable: 我在字符串变量中定义了一个JavaScript对象:

const str = "{a:1}";

I wonder what is the best way to convert it to a javascript object. 我想知道什么是将其转换为javascript对象的最佳方法。 I have searched a lot but all I found is to use JSON.parse or JSON.stringify to convert the string. 我进行了很多搜索,但发现的全部是使用JSON.parseJSON.stringify转换字符串。 But the tricky part in this string is that it is not a JSON object. 但是此字符串中的棘手部分是它不是JSON对象。 The a is not quoted. a没有加引号。 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. 我知道我可以手动解析字符串,但是我正在寻找一种更通用的解决方案来支持解析所有可能的javascript对象字符串。

var obj = eval(str);

Just be aware that using eval can have performance and security impacts. 请注意,使用eval会对性能和安全性产生影响。

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. 如果您不控制str的内容,即它是用户输入或来自您不信任的服务器,则存在风险。

Also, the JavaScript runtimes optimizes your code at runtime, but often disable many optimizations when engineering an eval . 此外,JavaScript运行时会在运行时优化代码,但在设计eval时通常会禁用许多优化。

Try to wrap the evaluation statement in a self invoked function that receive the variable passed to the eval : 尝试将评估语句包装在一个自我调用的函数中,该函数接收传递给eval的变量:

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

It ensures the creation of a closure to isolate the eval , mitigating it's potential impacts. 它可以确保创建一个隔离来隔离eval ,从而减轻其潜在影响。

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. 最后,不要说我刚才所说的任何话,这是绝对的事实:可以确定是否使用eval对代码进行基准测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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