Impostor JSON

Uncategorized

This tip will definitely help some of you out.

When creating JSON-formatted data, it seems as if you can omit quoting the keys:

{ name: "Anthony", reading: "The Wisdom Of Crowds" }

…although technically this is not JSON, as the key values are not quoted. However, you’ll see lots of examples floating around that use the non-key-quoting system. And it works in a lot of cases.

However, I ran into this code in Douglas Crockford’s JSON library for Javascript that was failing:

if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { /* ... */ }

Ha! Ha! Ha! Figuring out the error in this code is sort of like figuring out what smells in a landfill. But, it was easier than I thought. What was happening was that the string I was sending in to parse to JSON did not have the keys wrapped in double quotes, so the Crockford script failed, thinking it was not a valid JSON string.

Morals:

  1. Firebug is your friend.
  2. Type safety is your friend.
  3. Generic “syntax error” exceptions are not your friend, particularly when you’re chaining four calls together in one line.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • Ma.gnolia
  • Reddit
  • TwitThis
2 Comments

1 Comment

  1. Douglas Crockford  •  Feb 21, 2008 @2:33 pm

    The role of http://www.json.org/json2.js is not to be a developer’s friend. Its role is to defend users from developers.

    The developer’s friend is JSLint. It would have told you exactly what your problem was.

1 Trackback

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">