2

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?

2 Answers 2

5

I hit the same problem, here is how I did it with Jint

        var engine =new Engine();

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


        var doc=new HtmlDocument();
        doc.LoadHtml(html);
        var script = doc.DocumentNode.SelectNodes("//script").First().InnerHtml;

        var result = engine
            .Execute(script)
            .Execute("var x=apiresult.data.jsonData;")
            .GetValue("x");

        var jsonData = engine.Json.Stringify(result, new[] { result });
4

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.