Tim Gittos

I'm an Australian currently living in Austin, TX in the USA.

I currently earn a living programming, though I wouldn't call myself a programmer. If I had to attach a label to myself, I'd use the term autodidact.

I love learning, and my favorite things to learn about are programming, computer graphics, AI & machine learning, robotics, painting and creativity.

Evaluating JSON in Safari

Last updated on 13 Aug 2010

Just a quickie on parsing JSON strings in Safari.

I’m in the middle of a project developing a timesheet/rostering application, which uses a lot of Javascript. I have a series of web services that interact with jQuery. For reasons beyond the scope of this post, the web service returns a JSON string, which needs to be parsed into a JSON object, and then further processing is done on the object.

I had a bug where Safari was choking on the JSON string returned by my webservice, yet Firefox and IE were happy parsing it. As it turns out, my JSON string had a Javascript keyword in it; ‘break’.

Here is my JSON string (well, an example):

{employee: 'Joe', worked: true, periods: [{start: '09:00 AM', finish: '17:00 PM'}], break: {paid: true, hours: '1'}}

Safari was choking on the break in the above JSON string.

When I wrapped the attribute in single quotes, like so:

{employee: 'Joe', worked: true, periods: [{start: '09:00 AM', finish: '17:00 PM'}], 'break': {paid: true, hours: '1'}}

it was happy.

You can replicate this by using the below code snippet to parse out your JSON string quickly in Safari’s debug window:

var json = "{employee: 'Joe', worked: true, periods: [{start: '09:00 AM', finish: '17:00 PM'}], break: {paid: true, hours: '1'}}";
var obj = (new Function("return " + json))();

which should fail. If you add the single quotes around break though, it should work just fine.

This also fails for other Javascript keywords:

(new Function("return " + "{if: true}"))();

fails. If you wrap if in single quotes, it works.

I think the take away lesson is to always wrap your object attributes in a JSON string in single quotes, otherwise Safari will choke on it.