Is there any way to validate JSON before decode?

actionscript-3, air, flash, json

Solution

Use try.. catch...

import com.adobe.serialization.json.JSONParseError;

try
{
var jsonArray:Array = JSON.decode(loader.data);
}
catch ( e:JSONParseError )
{
    //do something
    trace(e);
}
finally
{
}

This solution uses as3corelib (http://as3corelib.googlecode.com/), if you use JSON.parse() please check the answer from JayC

Problem

I have an app that download a file and then decode it expecting a JSON format, when the format is ok everything goes well. If i intentionally mess the json file flash reports a format error and stop the app. Is there a way to handle the error? Code: ``` import flash.display.Sprite; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import com.adobe.serialization.json.JSON; public class Main extends Sprite { private var _jsonPath:String = "json_example.txt"; public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest(); request.url = _jsonPath; loader.addEventListener(Event.COMPLETE, onLoaderComplete); loader.load(request); } private function onLoaderComplete(e:Event):void { var loader:URLLoader = URLLoader(e.target); var jsonArray:Array = JSON.decode(loader.data); } ``` You see my problem is right at the end where `var jsonArray:Array = JSON.decode(loader.data);` How can I handle in my code if that fails?

Original source