Well, I have a lot of variables in javascript that I need get the values(that I getting from other page).
What’s the best way to do this?
I’m using the Microsoft.Jscript class and your methods for it work.
I written the following code:
static Dictionary<string, string> ParseVariables(string code)
{
string[] variables = code.Split(';');
Dictionary<string, string> variablesValues = new Dictionary<string, string>();
for (int i = 0, len = variables.Length - 1; i < len; i++)
{
string vvar = variables[i];
string varName = Regex.Replace(vvar.Split('=')[0], @"^\s*var\s*", string.Empty).Trim();
var compiler = Compile(vvar);
string varValue = compiler.ToString();
variablesValues.Add(varName, varValue);
}
return variablesValues;
}
static object Compile(string JSource)
{
return Microsoft.JScript.Eval.JScriptEvaluate(JSource, Microsoft.JScript.Vsa.VsaEngine.CreateEngine());
}
This works fine to some cases,like:
var jscript = "var x = 'foo'; var y = 'baa';";
var output = ParseVariables(jscript);
var val = output["y"]; //baa
var val2 = output["x"]; //foo
but to cases like this:
var jscript = "var x = {}; x['foo'] = 'baa'; x['baa'] = 'test';";
var output = ParseVariables(jscript);
var val = output["x['foo']"]; //not works
How I do this? Any help is appreciated! Thanks!
Since your approach is to split the JScript source code in chunks separated by semicolon (;), only the part between
varand;will be compiled using your Compile method.If you change your JScript source code into
var x = { "foo": "baa", "baa": "test" };, the Compile method will work properly, and it will return a ScriptObject object.But then, there is another error – you are using
ToStringbefore you insert the value into the resulting Dictionary.Try this out to get started in a better direction:
Change the Compile method into returning
ScriptObject, like this:Then try this: