« How I Debug with Flex Modules Flex 2.0.1 Hotfix 3 - The WebService Fix »

July 05, 2007

Parse errors with ActionScript 3's JSON library

I've had a few people ping me recently about unexpected parse errors they've encountered while decoding JSON strings using the ActionScript 3 JSON library (part of as3corelib). The fix is easy, but not entirely obvious.

It turns out that in all of the cases where erroneous parse errors were reported, the JSON string looked something like this:

{ prop1: 12, prop2: "hello, world" }

Can you spot the problem?

According to the JSON spec, the above snippet is not actually valid JSON. The reason? It's because the object property identifiers are not string literals. It may be valid JavaScript/ActionScript for creating an object via a literal, but JSON objects contain pairs of string : value and strings are always enclosed in double quotes.

The ActionScript 3 JSON parser I made is a bit on the strict side, I guess. From what I can gather, a lot of JSON decoders will accept the above snippet as valid JSON. Even worse, a lot of JSON encoders will produce JSON in the above format. That is, when you create a JSON string, behind the scenes the JSON string might not actually be valid. Typically the libraries that produce snippets without quotes around object identifiers will also accept those as valid input, so it's usually not a problem.

So, if you're running into parse errors when trying to decode JSON strings in ActionScript 3... make sure the JSON string is actually valid. The first place to look is for quoted identifiers in objects.

If you're using Ruby on Rails and running into this problem, a simple configuration change on the server end will fix the problem:

>> ActiveSupport::JSON::unquote_hash_key_identifiers=false
=> false

Thanks to Richard Wallace for pointing out the Rails configuration change necessary to produce valid JSON for the ActionScript 3 JSON decoder.

Tags: , , , ,

Comments

  • A more formal spec for JSON is here:
    http://tools.ietf.org/html/rfc4627

    It looks like a string cannot be enclosed in single quotes, either.

Post a comment

Remember personal info?