Reputation: 2064
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?
Upvotes: 2
Views: 3655
Reputation: 7285
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 });
Upvotes: 5