Evaluating JSON in Safari
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.