Because I blew a few hours trying to figure this out the last few days, and finally cracking it, here’s how to fetch some JSON from a web service and have it processed into an object in ActionScript 2.
import JSON; // http://www.theorganization.net/work/jos/JSON.as
var jsonFetcher:LoadVars = new LoadVars();
jsonFetcher.onLoad = function(success:Boolean) {
if (!success) {
trace("Error connecting to server.");
}
};
jsonFetcher.onData = function(thedata) {
// ...
// if writing a desktop app or widget, string manip or regexp
// the JSON data packet out of the JS source provided by many
// web services at this point..
// ...
try {
var o:Object = JSON.parse(thedata);
//mytrace(print_r(o));
trace(print_a(o));
} catch (ex) {
trace(ex.name+":"+ex.message+":"+ex.at+":"+ex.text);
}
};
// get the feed
jsonFetcher.load("url-to-json-feed.php");
// from: http://textsnippets.com/posts/show/633
// recursive function to print out the contents of an array similar to the PHP print_r() function
//
function print_a(obj, indent) {
if (indent == null) {
indent = "";
}
var out = "";
for (item in obj) {
if (typeof (obj[item]) == "object") {
out += indent+"["+item+"] => Objectn";
} else {
out += indent+"["+item+"] => "+obj[item]+"n";
}
out += print_a(obj[item], indent+" ");
}
return out;
}
BTW, what’s up with these JSON feeds that serve up JS that’s JSON plus some more code? That’s annoying — you gotta strip it out before you run the JSON converter .
Update: here’s the actionscript 2.0 JSON.as file people were looking for.