TExcelTAD
Home › MATLAB / Octave › JSON Data

JSON Data

JSON (JavaScript Object Notation) is the most common text format for exchanging structured data: web APIs return it, configuration files use it, and almost every language can read and write it. MATLAB (R2016b and later) and GNU Octave (7 and later) share two built-in functions:

Function Does
jsonencode(value) MATLAB value → JSON text (a char array)
jsondecode(text) JSON text → MATLAB value (struct, array, cell…)

No toolbox is needed, and both functions behave the same way in MATLAB and Octave for everyday data. If JSON itself is new to you, the JSON course explains the syntax.

Encoding: MATLAB to JSON

A structure becomes a JSON object, its fields become keys, and numeric vectors become JSON arrays:

matlab · try it yourself
person = struct('name', 'Ann', 'age', 31, 'scores', [90 85 77], 'active', true);
txt = jsonencode(person);
disp(txt)
disp(class(txt))
disp(jsonencode([1 2; 3 4]))
disp(jsonencode({1, 'two', false}))
disp(jsonencode(struct('name', {'Ann', 'Bob'}, 'age', {31, 27})))
{"name":"Ann","age":31,"scores":[90,85,77],"active":true}
char
[[1,2],[3,4]]
[1,"two",false]
[{"name":"Ann","age":31},{"name":"Bob","age":27}]
MATLAB value JSON
scalar number, true/false number, true/false
numeric or logical vector array [1,2,3] (row and column vectors alike)
matrix nested arrays, one inner array per row
char array string "text"
cell array array of whatever each cell holds
scalar struct object {"field": value}
struct array array of objects
[], {} []
NaN, Inf null
containers.Map object (keys can be any text)

The edge cases worth knowing

A one-element vector is just a scalar in MATLAB, so jsonencode writes it as a plain number. If the receiver expects an array, wrap it in a cell. Empty values become [], and NaN becomes null because JSON has no NaN:

matlab · try it yourself
disp(jsonencode(struct('ids', 7)))
disp(jsonencode(struct('ids', {{7}})))
disp(jsonencode(struct('ids', [])))
disp(jsonencode([1 NaN Inf]))
disp(jsonencode(struct('note', 'say "hi"\ok')))
m = containers.Map({'first-name', 'age'}, {'Ann', 31});
disp(jsonencode(m))
{"ids":7}
{"ids":[7]}
{"ids":[]}
[1,null,null]
{"note":"say \"hi\"\\ok"}
{"age":31,"first-name":"Ann"}

Quotes and backslashes inside text are escaped automatically. A containers.Map (see Key-Value Maps) is the way to produce keys such as first-name that aren't valid MATLAB field names; its keys come out sorted.

Warning: Octave 11 mishandles numbers that don't fit in a 64-bit integer (for example, jsonencode(1e20) gives -9223372036854775808), and the last digit of values like 0.1 + 0.2 can differ from MATLAB's. Round values to the precision you need before encoding, and send very large numbers as text if exactness matters.

Decoding: JSON to MATLAB

jsondecode picks the most convenient MATLAB type for each part of the document:

matlab · try it yourself
txt = '{"name":"Ann","age":31,"tags":["admin","dev"],"scores":[90,85,77],"address":{"city":"Lyon"}}';
p = jsondecode(txt);
fprintf('%s, %d, lives in %s\n', p.name, p.age, p.address.city);
disp(class(p.tags))
disp(p.tags')
disp(size(p.scores))
fprintf('mean score %.2f\n', mean(p.scores));
Ann, 31, lives in Lyon
cell
{
  [1,1] = admin
  [1,2] = dev
}
   3   1
mean score 84.00
JSON MATLAB result
object scalar struct
array of numbers column vector (null elements become NaN)
array of booleans logical column vector
array of equal-length number arrays matrix
array of objects with the same keys struct array (Nx1)
array of objects with different keys, or mixed types cell array (Nx1)
array of strings cell array of char (Nx1)
string char array
null []

Two details surprise people: numeric arrays come back as columns even though they were written as rows, and the type of an array depends on its contents, so a list of records can be a struct array in one response and a cell array in the next if one record has an extra key.

matlab · try it yourself
same = jsondecode('[{"id":1,"tag":"a"},{"id":2,"tag":"b"}]');
fprintf('%s %dx%d\n', class(same), size(same, 1), size(same, 2));
disp([same.id])
mixed = jsondecode('[{"id":1},{"id":2,"tag":"b"}]');
fprintf('%s %dx%d\n', class(mixed), size(mixed, 1), size(mixed, 2));
disp(mixed{2}.tag)
M = jsondecode('[[1,2,3],[4,5,6]]')
gaps = jsondecode('[1, null, 3]')'
struct 2x1
   1   2
cell 2x1
b
M =

   1   2   3
   4   5   6

gaps =

     1   NaN     3

Code that reads data from an outside source should handle both shapes. A robust pattern is to turn a struct array into a cell array first, so the rest of the code always loops over cells:

matlab · try it yourself
txts = {'[{"id":1},{"id":2}]', '[{"id":3},{"id":4,"extra":true}]'};
for t = 1:numel(txts)
    recs = jsondecode(txts{t});
    if isstruct(recs)
        recs = num2cell(recs);
    end
    ids = cellfun(@(r) r.id, recs);
    fprintf('batch %d: ids %s\n', t, mat2str(ids'));
end
batch 1: ids [1 2]
batch 2: ids [3 4]

Keys that aren't valid field names

JSON keys can contain spaces, dashes or start with a digit, but MATLAB field names can't. jsondecode makes them valid (as matlab.lang.makeValidName would): spaces are removed and the following letter is capitalised, other invalid characters become underscores, and a leading digit gets an x prefix.

matlab · try it yourself
s = jsondecode('{"first-name":"Ann","2fa":true,"zip code":"69001"}');
disp(fieldnames(s)')
fprintf('%s / %d / %s\n', s.first_name, s.x2fa, s.zipCode);
{
  [1,1] = first_name
  [1,2] = x2fa
  [1,3] = zipCode
}
Ann / 1 / 69001

Encoding such a struct again writes the modified names (first_name), so a round trip doesn't restore the original keys. If you need the exact keys back, build a containers.Map before encoding.

Pretty printing

By default jsonencode produces compact text on a single line. MATLAB R2021a added an option for human-readable output with indentation:

matlab
% MATLAB R2021a or later
cfg = struct('name', 'demo', 'version', 2, 'tags', {{'a', 'b'}});
disp(jsonencode(cfg, 'PrettyPrint', true))

MATLAB output:

text
{
  "name": "demo",
  "version": 2,
  "tags": [
    "a",
    "b"
  ]
}

Octave accepts the same option, but whether it works depends on how Octave was built: the build used for this course prints a warning ("support for the PrettyPrint option of RapidJSON was unavailable") and returns compact text. A small function that indents compact JSON works everywhere. It walks the text once, keeps track of whether it is inside a string, and starts a new line after {, [ and ,:

matlab · try it yourself
cfg = struct('name', 'demo', 'version', 2, 'tags', {{'a', 'b'}});
disp(pretty_json(jsonencode(cfg)))

function out = pretty_json(txt)
out = '';
depth = 0;
inString = false;
k = 1;
while k <= numel(txt)
    ch = txt(k);
    if inString
        out(end+1) = ch;
        if ch == '\'
            out(end+1) = txt(k + 1);
            k = k + 1;
        elseif ch == '"'
            inString = false;
        end
    elseif ch == '"'
        out(end+1) = ch;
        inString = true;
    elseif ch == '{' || ch == '['
        depth = depth + 1;
        out = [out ch newline repmat(' ', 1, 2 * depth)];
    elseif ch == '}' || ch == ']'
        depth = depth - 1;
        out = [out newline repmat(' ', 1, 2 * depth) ch];
    elseif ch == ','
        out = [out ',' newline repmat(' ', 1, 2 * depth)];
    elseif ch == ':'
        out = [out ': '];
    else
        out(end+1) = ch;
    end
    k = k + 1;
end
end
{
  "name": "demo",
  "version": 2,
  "tags": [
    "a",
    "b"
  ]
}

The output matches MATLAB's PrettyPrint layout for this example (empty arrays and objects would get a blank line, which a real formatter would special-case).

Reading and writing JSON files

There is no special file function: write the text with fprintf, and read it back with fileread, which returns the whole file as one char array:

matlab · try it yourself
data = struct('station', 'North', 'readings', [12.5 13.1 12.8], 'ok', true);
fid = fopen('station.json', 'w');
fprintf(fid, '%s\n', jsonencode(data));
fclose(fid);

raw = fileread('station.json');
fprintf('file has %d characters\n', numel(raw));
back = jsondecode(raw);
fprintf('%s: max %.1f\n', back.station, max(back.readings));
disp(isequal(back.readings', data.readings))
delete('station.json');
file has 58 characters
North: max 13.1
1

The round trip restores the values, but remember that readings came back as a column, hence the transpose before comparing. See Reading & Writing Text Files for fopen and fprintf in detail.

In MATLAB, webread(url) fetches a web API and decodes its JSON response in one step, and webwrite sends data; Octave has webread too but these need a network connection, so they aren't run here:

matlab
% Not run here (needs network access)
info = webread('https://api.example.com/v1/status');   % returns a struct

Learn more: Structures, Cell Arrays, Key-Value Maps and the JSON course.

Test yourself

What does jsondecode('[1, 2, 3]') return?

  1. A 3x1 column vector
  2. A 1x3 row vector
  3. A cell array
  4. A struct

How do you make jsonencode write a single number as an array, e.g. [7]?

  1. Wrap it in a cell: {7}
  2. Use [7]
  3. Use int8(7)
  4. It's impossible

What field name does jsondecode create for the JSON key "first-name"?

  1. first_name
  2. firstname
  3. first-name
  4. x1