File Exchange

image thumbnail

C++ JSON IO

version 2.0.0.0 (5.63 KB) by Oliver Woodford
Mex wrapper to C++ class for fast reading and writing of JSON files

5 Downloads

Updated 13 Apr 2017

View License

These function wrap Niels Lohmann's JSON for Modern C++ class into mex wrappers, for fast reading of JSON files into MATLAB variables, and writing MATLAB variables into JSON files.
JSON for Modern C++ must be downloaded separately from:
https://github.com/nlohmann/json

Mex these functions by calling:
mex json_read.cpp
and
mex json_write.cpp
Note that your C++ compiler must support C++11.

Example usage: var = json_read(filename)
IN:
filename - String of filename (if in current directory) or full or relative path to the JSON file to be read in.
OUT:
var - MATLAB interpretation of the JSON data.

Comments and Ratings (7)

json_write cannot be compiled as is. Include the "iomanip" and the "sstream" header files to compile it successfully.

Hi there, I cannot compile your code. Could you provide a pre-build version?

Wyfi Mcfly

Craig Cole

Very happy, was able to use this with coder. Must indicate not to compile the mex code, and then predefine the structure expected (and turn off warning that it's going to be overwritten)

Assuming my_settings.json is:

{"x": 15}

In Matlab:

coder.extrinsic('json_read');
result.x = 0; %#ok<STRNU>
result = json_read('my_settings.json');

I suspect faster performance still can be achieved using the SAX API of the header only RapidJSON C++ library. https://github.com/miloyip/rapidjson/

Oleg: On the single 8MB file I have just tested it on, calling matlab.internal.webservices.fromJSON(fileread('myfile.json')) in R2016a is over 10 times slower than calling json_read (using timeit for the timing). This is no guarantee of performance on other files, of course.

Oleg Komarov

How does it compare to the now (since R2016a) mexed version of matlab.internal.webservices.fromJSON()?

Updates

2.0.0.0

Update description

2.0.0.0

Added json_write

1.0.0.0

Removed JSON library from file for licensing reasons. Must now be dowloaded separately.

1.0.0.0

Add new paragraph

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Tags Add Tags

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.


Learn About Live Editor