AS3 JSON library now a little less strict

| No Comments | No TrackBacks
I've just checked in revision 83 of as3corelib that adds a strict flag to the AS3 JSON library.  In the past the library would generate an error if the JSON string was deemed invalid according to the syntax rules.  Now, based on the strict flag setting, the parser does a better job at allowing "valid" input even if the input doesn't match the JSON spec.

I've actually had this code completed since MAX 2008.  I wrote it on my flight from San Fransisco to Harrisburg, but haven't had the time to get it ready for check-in until now.

Here is the commit message:

  • Added throwing error if entire string cannot be consumed (when there are remaining characters left in the input stream)
  • Added "strict" flag to decoding process.  Default is true for backwards compatibility.  When false, relaxes input format rules.  Fixes #34, Fixes #41, Fixes #71:
    • Allows for hex specification for numbers, ex: { "myNum": 0xFFCC33 }
    • Allows for NaN to be parsed as a number, ex: { "myNum": NaN }
    • Allows for trailing commas in arrays, ex: [1,2,]
    • Allows for trailing commas in objects, ex: { "p1":true, "p2":false, }
    • Does not throw error if there were characters left in the input string
  • Added tests for strict flag
  • Added tests to better exercise comments
  • Updated tests to use proper assert types
  • Some minor cosmetic code cleanup
Usage is exactly the same as before, with the additional option of specifying the strict flag as part of the JSON.decode( string, strict ) call.  Example:

// Set strict mode to false to allow for trailing commas to not throw an error
var o:Array = JSON.decode( "[0,1,]", false ) as Array;
assertEquals( 0, o[0] );
assertEquals( 1, o[1] );

// Same usage as before, strict mode will throw a runtime error if the string is not valid
var a:Array = JSON.decode( "[0,1,]" ) as Array;

I still need to address #35 to allow for unquoted keys in objects to be parsed in non-strict mode.  This is a bit more complicated of a change because it changes how the tokenizer recognizes what is in the input stream.  It's coming though!

Note that a new .swc file was not yet posted.  If you want to experiment with these changes, you'll have to pull the latest from source.  I'll work with Mike to get the download .swc updated soon.

No TrackBacks

TrackBack URL: http://www.darronschall.com/mt/mt-tb.cgi/162

Leave a comment



About this Entry

This page contains a single entry by darron published on December 23, 2008 10:16 AM.

Hello World 2.0 was the previous entry in this blog.

Flex 2.0.1 SDK is dying is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Archives

OpenID accepted here Learn more about OpenID
Powered by Movable Type 5.02