简体   繁体   中英

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? 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('var variable1 = JSON.parse(\'{"bla": "blabla"}\')');

Just take care to escape quotation marks properly (see Replacing quotation marks in Javascript? ).

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. 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\"; ");

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