The Microsoft ScriptControl and JavaScript Evaluation
January 02, 2007 • about 2 minutes to read
I’m screwing around with JSON parsing in one of my FoxPro apps at the moment. Sometime ago I built a JSON parser for VFP and it works well enough for outbound JSON generation, but I don’t have a good solution for inbound JSON. JSON is merely a text encoding of values, but it can be nested and parsing this string is not trivial.
The problem is that VFP lacks decent language support for building a state machine parser because there’s no efficent way to access each character in a string efficiently. The only mechanism to parse a string character by character is with SUBSTR() which is dreadfully slow!
So I got a bright idea earlier today: Windows actually ships with a JavaScript engine and a script control that makes it relatively painless to execute and parse JavaSCript code. So why not take advantage of this control to handle the parsing for me. The control includes a handy Eval method:
o = CREATEOBJECT("ScriptControl")
o.Language="JScript"
? o.Eval("'Hello \r\n WOrld'")
? o.Eval("100.11")
? o.Eval("true")
? o.Eval("false")
loResult = o.Eval([new Date("Mon, 1 Jan 2007 23:09:09 -1000")])
? loResult.toString()
loResult = o.Eval([{"x":10,"y":15}])
? loResult.x
Took a while to find some documentation on this control – it’s not widely used apparently. I was happy to see that the control works and can parse simple values. However, it choked on the complex expressions. The string, numeric and logical values parsed easily enough (and strings are nice to have parsed that way BTW because of the encoding).
But I was unable to get the date to parse. I do get a result of type object back, but I’m unable to do anything with this date in FoxPro. I tried using JavaScript date methods like toString(), getTime() etc. but none of that worked. I also tried things like name, id, class and a host of common container properties, but none of that would work either. Even COMCLASSINFO() wouldn’t return me a ClassID. Whatever this object is – I can’t figure out what the heck it is or what to call on it.
In fact it didn’t like this either:
loResult = o.Eval([{"x":10,"y":15}.toString()])
? loResult
So the problem is more deep seated in that apparently Jscript can’t deal with JavaScript 1.2 syntax which is required for this object syntax. Bummer as that pretty much breaks all hopes of it being useful for parsing.
So I’m back to manually doing this – possibly looking at some fancy RegEx parsing of string chunks at a time. Drat…
Christof Wollenhaupt
January 02, 2007