0

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?

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
ShayD
  • 689
  • 7
  • 17

2 Answers2

2

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?

Community
  • 1
  • 1
oberbics
  • 408
  • 4
  • 12
  • Thanks. eval was what I was looking for. Unfortunately, that didn't work with the string I was trying to evaluate even though I escaped the quotation marks as mentioned. I gave it up since I found the data elsewhere. – ShayD Jul 18 '16 at 05:59
1

you can:

eval("var variable1 = JSON.parse('{\"bla\": \"blabla\"}'); var variable2 = \"some string\"; ");
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Michal Toldy
  • 175
  • 7
  • [**eval is evil**](https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/) – Anik Islam Abhi Jul 14 '16 at 06:34
  • Sure, eval is evil, but it does answer the OP's question pretty directly. Perhaps there are some "safe" libraries out there that are available to do this kind of string parsing. – Josh Beam Jul 14 '16 at 06:36