Search code examples
c#jint

Interpret/parse Javascript Variables in c# with JInt or similar


I'm attempting to build an application that uses an API that was made for JavaScript. Rather than sending down JSON or XML it sends a Script tag with a JavaScript object within it like so:

<script>
var apiresult = {
    success: true,
    data: {
        userName: "xxxxx",
        jsonData: { 
            "id" : "8342859",
            "price" : "83.94"
            }
        }
    };
</script>

I'm trying to get out just the "jsonData" property. In browser land you can go:

apiresult.data.jsonData;

Obviously I can't do this in C#. I've tried using Jint and HtmlAgilityPack like so:

HtmlDocument = await client.GetHTMLAsync(url);

string scriptTag = htmlResult.DocumentNode.SelectNodes("//script").InnerHtml;

scriptTag += " return apiresult.data.jsonData;

JintEngine engine = new JintEngine();

Jint.Native.JsObject r = (Jint.Native.JsObject)engine.Run(scriptTag);

And if I expand "r.Results" in the watch window it shows the variables values, but how do I then get just the raw JSON back out so that I can parse it into my object?


Solution

  • In the end I used jurassic to do this. Much much easier to use than JInt. My code now looks like this:

    ScriptEngine engine = new ScriptEngine();
    
    object result = engine.Evaluate(scriptString);
    
    var json = Jurassic.Library.JSONObject.Stringify(engine, result);