Zach’s ugly mug (his face)

Zach Leatherman

Javascript Objects are NOT JSON

09 May 2008 Read in about 2 minutes

The headline should more accurately read “Javascript Objects are not necessarily JSON.” But that waters it down a bit, don’t you think?

I know this has been posted a few times before, but this is not something I knew until recently, and after learning it, have noticed quite a few other people doing it wrong as well. So, to risk adding another reverb to the echo chamber, I’ll post a link to a good explanation by Jesse Skinner on the specifics of the JSON specification.

The main point here is that all object keys and strings in JSON must have double quotes. I encourage you to look through the train track specification to verify for yourself.

If you try to use Captain Crockford’s JSON Parser, it won’t parse your string with single quotes or (un/single)-quoted object keys. His parser has a nice regex checker built-in (and a walker callback to let you parse date strings into Date() objects). It’s a good way to verify that external data, or a data source not under your control, is safe to eval and use in your own code.

Here are a few quick examples:

Valid JSON

{"myKey": "myString"}

Don’t use single quotes. Don’t use unquoted object keys.

Invalid JSON

{myKey: "myString"}
{'myKey': 'myString'}

Credits to Jonathan Snook for the initial write-up and Crockford for formalizing JSON.


➡ Load Disqus to Leave a Comment ⬅

Comment modified by admin.

Javascript objects are not JSON full stop. JSON is a means of representing Javascript data in plain text format. JSON is text, Javascript objects are... well... Javascript objects!

Saying they are alike is like saying that by me sending you the text "$1M Australian dollars" I have given you a million dollars. I'll give you details on how you can give that million bucks back to me via a wire transfer if you care to argue your point of view any further. ;-)

Zach Leatherman

02 Jul 2008 at 12:21PM

I think you are making a critical mistake in assuming that the things that you have learned in the past are obvious to everyone.

Thanks for your comment.

It's funny - I've known JSON for a while, but it wasn't until recently (last year, I think?) that I realized just how strict the JSON standard actually is.