Matlab interface with JSON data

Interfacing with different types of data is important, and JSON (for whatever reason) seems to be a popular format. For the past couple of years we have used JSONLab Mathworks File Exchange like many other folks out there, and yes it is good!

However, one of the problems with the JSON format is that it repeats the key (as in key-value concept) for every element and is thus quite redundant. This also makes the JSON file bulky, and complicated deep JSON files (lists of dictionaries of lists of dictionaries, you get the idea…) take forever to parse.

Thanks to Christian Panton, there is now a matlab-json repository on Github which uses the json C/C++ libraries, creates a MEX file, and thus makes reading a JSON file very fast.

All timing is computed as the average of 10 runs when not mentioned otherwise. It includes the time taken to open and read the JSON file (both use fscanf in Matlab). For a relatively small JSON file 9.3KB which has a simple structure array, JSONLab takes roughly 220 milliseconds, while matlab-json takes 9.6 milliseconds. That’s a massive improvement for a small file. For a file with complexity depth 2 (structure array of structure) and size 9.0MB, JSONLab takes 4869 seconds! (that’s 1h20min, computed on 1 run) while matlab-json takes just 1.54 seconds.

The repository includes a binary for windows (I haven’t tested) and is easy to compile for linux. Just install libjsoncpp-dev, libjson-c-dev and you are good to go with the make.m. To maintain compatibility with JSONLab’s “loadjson” which can directly take a filename as input, you may need to wrap matlab-json’s “fromjson” to try and read from file first.

You can now use big and ugly JSON files with your Matlab.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s