File Exchange

image thumbnail

Structure to JSON

version (3.42 KB) by Lior Kirsch
Saves a structure in JSON format


Updated 23 May 2015

View License

Saves the values in the structure 'data' to a file using JSON format.
Example: = 'chair';
data.color = 'pink';
data.metrics.height = 0.3;
data.metrics.width = 1.3;
saveJSONfile(data, 'out.json');

Output 'out.json':
"name" : "chair",
"color" : "pink",
"metrics" : {
"height" : 0.3,
"width" : 1.3

Cite As

Lior Kirsch (2020). Structure to JSON (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (14)

Yunzhi Lin

I think people should use the official function jsonencode instead. This one does not have good support for multiple rows structure.

Mohammed Hijjo

I am wondering if it really works with multiple rows structure! I just tried it out and it just converted/encoded the first row of my structure!
Did anyone test it carefully? or got the same experience!
Best regards and thanks in advance

Giacomo Echevers

Adrian Hood


Simple and does the trick. Thanks Zane Rau and Daniel Grötsch for updates.

David Fardis

Like it. The online tool for minifying data

Daniel Grötsch

Great part of code. I fixed the evals by replacing code with currentElementValue = data.(currentField); %eval(sprintf('data.%s',currentField)); (as suggested by Zane Rau), and fixed not working for arrays by replacing the code after if length(currentElementValue) > 1 && ~ischar(currentElementValue) with the following one liner
fprintf(fid,'"%s" : "%s"' , currentField,jsonencode(currentElementValue));

Veronika Cheplygina

Does not appear to work when the value is an array, cuts off at the opening bracket


Zane Rau

Zane Rau

Almost perfect. Anyone using this should change out the 2 "eval" lines with the following....
currentElementValue = data.(currentField)
eval is not good to use, especially with such an easy work around in sight.


Bryan O'Neill

Javier Ortiz

k x


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

Inspired: Structure and object to JSON