I'm struggling with passing a JSON object to a .swf via FlashVars and decoding the JSON FlashVars in AS3 and was hoping you could help me.
Problem:
I get an JSONParseError: Unexpected o encountered
when I try to decode the FlashVars.
Situation:
A PHP function creates paths to images from a hash and puts them together in this JSON object:
[{"index":"0", "path":"image1", "ext":"jpg"},
{"index":"1", "path":"image2", "ext":"jpg"},
{"index":"2", "path":"image3", "ext":"jpg"}]
This JSON is passed to .swf via Flashvars. In the HTML I have this:
<param name="FlashVars" value='[{"index":"0", "path":"image1", "ext":"jpg"},{"index":"1", "path":"image2", "ext":"jpg"},{"index":"2", "path":"image3", "ext":"jpg"}]'/>
The PHP function and the .swf are in the same folder on the webspace
Then I try to decode the FlashVars in my main.as file with this AS3 Code (as3corelib is imported):
var imagePaths:Object;
try {
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
trace(paramObj.toString());
if(paramObj){
imagePaths = JSON.decode(paramObj.toString());
}
}
catch (error:Error)
{
trace(error.toString());
}
"imagePaths" holds the JSON object so later the paths to the images could be constructed. As far as I understood JSON.decode returns an This worked fine when I loaded the exactly same JSON on localhost from a separate txt file with:
var imagePathLoader:URLLoader = URLLoader(e.target);
imagePaths = JSON.decode(imagePathLoader.data);
The error obviously occurs in the try block, so I traced the paramObj variable with trace(paramObj.toString());
and get [object Object]
as output.
It seems to me that the JSON decode function is trying to decode the string [object Object]
rather than the object itself and therefore throws an error at the first "o" of "object"?
I already tried to urlencode() the JSON from PHP before passing as FlashVars, the suggestions found on http://code.google.com/p/as3corelib/issues/detail?id=119 and did JSON.decode(paramObj);
without .toString() which throws this error:
1118: Implicit coercion of a value with static type Object to a possibly unrelated type String.
So, how do I pass the JSON correctly to the .swf and decode it in AS3 to an object?
Thanks in advance for any help
Thanks for the replies..I also found this out yesterday but couldn't answer my own question for 8h (new user..). What I did: In the HTML file that embeds the swf:
<param name="FlashVars" value="var=urlencode([{"index":"0", "path":"image1", "ext":"jpg"},
{"index":"1", "path":"image2", "ext":"jpg"},
{"index":"2", "path":"image3", "ext":"jpg"}])"/>
then in the AS3 code I accessed the FlashVars with:
var imagePaths:Object;
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
var myFlashVar:String;
var varName:String;
for (varName in paramObj) {
myFlashVar = String(paramObj[varName]);
}
imagePaths = JSON.decode(myFlashVar);
then processed the JSON object as usual..thanks for your help!