[英]is there a way to convert js file or a script string to an object?
is there a way to convert a js file string to an object without string manipulations? 有没有一种方法可以将js文件字符串转换为对象,而无需进行字符串操作? i'm scrapping a script element from a page and want to use it as an object.
我正在从页面中删除脚本元素,并希望将其用作对象。 the string i get is something like:
我得到的字符串是这样的:
var variable1 = JSON.parse('{"bla": "blabla"}');
var variable2 = "some string";
and i want to use the first variable as an object. 我想将第一个变量用作对象。
is there an elegant way of doing this without too much text manipulations? 是否有一种优雅的方式来完成此操作而无需过多的文本操作?
You can use the eval function: 您可以使用eval函数:
eval('var variable1 = JSON.parse(\'{"bla": "blabla"}\')');
Just take care to escape quotation marks properly (see Replacing quotation marks in Javascript? ). 只是要注意正确地转义引号(请参阅替换Java中的引号? )。
Note: Some say eval is evil because it might happen that you are creating some security vulnerabilities by executing code you might not know whats it doing in advance. 注意:有人说eval是邪恶的,因为可能会发生是通过执行代码来创建一些安全漏洞,您可能不知道它事先在做什么。 But if it fits your needs, and you know what you are doing, why not?
但是,如果它满足您的需求,并且您知道自己在做什么,为什么不呢?
您可以:
eval("var variable1 = JSON.parse('{\"bla\": \"blabla\"}'); var variable2 = \"some string\"; ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.