NSJSONSerialization category to read JSON with comments

Before Apple added NSJSONSerialization in iOS 5, I’ve been using JSONKit to parse commented JSON configuration files in Textastic. I’ve been wanting to replace it with NSJSONSerialization for some time now. The fact that JSONKit’s direct access of the isa pointer made Textastic crash on OS X 10.10 Yosemite finally made me do the switch.

The biggest hurdle was my use of JKParseOptionComments:

Allow C style // and /* … */ comments in JSON. This is a fairly common extension to JSON, but JSON that contains C style comments is not strictly conforming JSON.

Unfortunately, NSJSONSerialization doesn’t have an option to ignore comments in JSON files.

This is where my “NSJSONSerialization+Comments” category comes in!

You can use this category’s JSONObjectWithCommentedData:options:error: method just like NSJSONSerialization’s JSONObjectWithData:options:error::

id object = [NSJSONSerialization JSONObjectWithCommentedData:data options:0 error:&error];

The code is tuned for performance and works directly on UTF-8 data without converting it to an NSString. It strips single line and multi-line comments as well as whitespace before it hands over the data to NSJSONSerialization.

It also detects UTF-16 and UTF-32 through their byte order marks (BOM): if a non-UTF-8 BOM is found, it converts the data to UTF-8 using NSString. UTF-8 is definitely recommended if you don’t want this overhead.

I’ve also added a few convenience methods to load JSON from a file or URL instead of NSData.

More information can be found at the NSJSONSerialization+Comments Github repository.