03 October 2017

Who knew than JSON.parse() requires double quotes

The other day we were trying to get a small app off the ground. Sometimes even the simplest things which should obviously work, just don’t work.

The code in question was creating a small object:

var s = '{';
s = s + 'width : 17,';
s = s + 'length : 20';
s = s + '}';

var o = JSON.parse(s);

But after executing, o did not contain an object at all.

(As I write this, call to JSON.parse(s) fails with an exception in Chrome. I am fairly certain that during the development there was no exception.)

After unsuccessfully trying out a few things, a search on the internet revealed that property names must be double quoted. This was a bit surprising, since one can easily asume that whatever Javascript code is valid, it will still be valid when passed as a string into JSON.parse()

Turns out JSON has special syntax which prescribes double quotes.