Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
MATLAB JSON Parsing and Formatting Functions
If you need to work with JSON in MATLAB, the core functions are straightforward: use jsondecode to parse JSON text into MATLAB data, and use jsonencode to turn MATLAB variables back into JSON. For direct file-based workflows, newer MATLAB releases also add helpers such as readstruct, writestruct, and readdictionary. For most search visitors, the real questions are usually how to decode formatted JSON text, how nested arrays of objects behave, and how to write a valid JSON file without losing structure. This page focuses on those practical cases.
Quick Answer: Which MATLAB JSON Function Should You Use?
- Use
jsondecodewhen you already have JSON text in memory and want MATLAB structs, arrays, or cell arrays. - Use
jsonencodewhen you want to serialize MATLAB data to JSON text, including pretty-printed output for logs, debugging, or saved files. - Use
filereadplusjsondecodeif you are reading a.jsonfile in any release that supports the JSON functions. - Use
readstructandwritestructin newer releases if you want MATLAB to read or write JSON files directly without manualfopen/fprintfcode. - Use
readdictionaryin R2024b or newer when preserving string keys matters more than mapping JSON objects into MATLAB struct field names.
jsondecode: Parse JSON Text into MATLAB Data
jsondecode accepts JSON text as a character vector or string scalar and converts it into the nearest MATLAB representation. That makes it the right tool for API responses, config files loaded with fileread, and any situation where you already have raw JSON text.
Example: Decode Nested JSON with Multiple Objects
A common MATLAB JSON question is how to handle an array of multiple child objects or nodes. If the objects in the JSON array have a compatible structure, MATLAB gives you a struct array that you can index naturally.
Example: jsondecode with Multiple Nodes
jsonText = ['{' ...
'"project":"demo",' ...
'"files":[' ...
'{"name":"input.csv","rows":12,"active":true},' ...
'{"name":"output.csv","rows":18,"active":false}' ...
']' ...
'}'];
data = jsondecode(jsonText);
firstName = data.files(1).name
rowCounts = [data.files.rows]
activeFlags = [data.files.active]
In this example, data is a struct, and data.files is a struct array with two elements because each JSON object in files has the same fields.
Does jsondecode Work with Formatted JSON Text?
Yes. Pretty-printed JSON with spaces and line breaks is still valid JSON, so jsondecode can parse it directly. In practice, the reliable MATLAB pattern is to read the whole file with fileread and pass that text to jsondecode.
Example: Decode Formatted JSON Text
formattedText = sprintf(['{\n' ...
' "user": "alice",\n' ...
' "settings": {\n' ...
' "theme": "light",\n' ...
' "autosave": true\n' ...
' }\n' ...
'}']);
config = jsondecode(formattedText);
mode = config.settings.theme
% When reading from disk:
config = jsondecode(fileread("config.json"));
Use fileread rather than fscanf(fid, '%s'). The latter reads whitespace-delimited text, which is a poor fit for multi-line JSON.
How jsondecode Maps JSON to MATLAB
- JSON objects decode to MATLAB structs.
- JSON arrays of numbers decode to MATLAB numeric arrays, typically
double. - JSON arrays of booleans decode to MATLAB logical arrays.
- JSON arrays of compatible objects often decode to struct arrays; mixed or incompatible content can decode to cell arrays instead.
- JSON strings decode to MATLAB character vectors.
- JSON
nullbecomesNaNinside numeric arrays, but becomes an empty array in nonnumeric positions. - JSON object keys that are not valid MATLAB identifiers may be adjusted when converted into struct field names.
jsonencode: Convert MATLAB Data to JSON
jsonencode converts MATLAB values into JSON text. It is the function behind most MATLAB JSON formatting tasks, whether you need compact output for transport or pretty-printed output for a readable JSON file.
Example: Encode a MATLAB Struct as JSON
Basic jsonencode Example
person = struct( ...
"name", "Alice", ...
"age", 30, ...
"isStudent", false, ...
"scores", [91 88 95]);
compactJson = jsonencode(person)
prettyJson = jsonencode(person, PrettyPrint=true)
In releases before R2021a, use quoted name-value syntax instead: jsonencode(person, 'PrettyPrint', true).
Special Values: NaN and Inf
By default, jsonencode converts NaN, Inf, and -Inf to null because strict JSON has no native representation for those numeric values. If you are targeting a consumer that accepts nonstandard tokens, MATLAB also supports a compatibility mode.
Example: Control How Nonfinite Numbers Are Encoded
values = struct("ok", 5, "missing", NaN, "upper", Inf);
strictJson = jsonencode(values)
compatJson = jsonencode(values, ConvertInfAndNaN=false)
strictJson is valid JSON. compatJson may emit tokens such as NaN or Infinity, which many parsers reject.
Write MATLAB Data to a JSON File
If your goal is simply "write to JSON file in MATLAB," the portable approach is still to encode the data first and then write the returned text to disk.
Example: Encode and Save JSON
settings = struct( ...
"mode", "auto", ...
"threshold", 0.75, ...
"enabled", true);
jsonText = jsonencode(settings, PrettyPrint=true);
fid = fopen("settings.json", "w");
fprintf(fid, "%s", jsonText);
fclose(fid);
If you need to read that file back later, use settings = jsondecode(fileread("settings.json"));
File-Based Helpers in Newer MATLAB Releases
MATLAB has added higher-level JSON file APIs beyond jsonencode and jsondecode. These are worth knowing because many users search for a MATLAB JSON reader or a direct JSON file writer, not just text conversion.
readstructcan read JSON files directly into a struct. MathWorks added JSON support for it in R2023b.writestructcan write structs to JSON files directly in R2023b and newer.readdictionarywas added in R2024b and is useful when you want JSON object keys to stay as keys instead of becoming MATLAB struct field names.
Example: Direct JSON File I/O in Newer Releases
% R2023b+
data = readstruct("payload.json");
writestruct(data, "payload-pretty.json", PrettyPrint=true);
% R2024b+
headers = readdictionary("headers.json");
One formatting detail that surprises people: jsonencode(..., PrettyPrint=true) uses two-space indentation, while writestruct(..., PrettyPrint=true) writes four-space indentation.
Common Pitfalls and Troubleshooting
- Invalid key names: JSON keys can contain characters MATLAB does not allow in struct field names. After
jsondecode, inspect the resulting field names carefully or usereaddictionaryin R2024b or newer. - Arrays of objects: If an array does not resolve cleanly to one struct layout, MATLAB may return a cell array instead of a struct array. Check with
classand index accordingly. - Formatted JSON from files: Prefer
filereadfor loading multi-line JSON text. It is simpler and more reliable than line-by-line or whitespace-delimited reads. - Strict vs nonstandard JSON:
jsondecodeexpects valid JSON syntax. Comments, trailing commas, and nonstandard numeric tokens are not safe inputs there. - MATLAB object serialization:
jsonencodeencodes public object properties, but complex custom classes may still need a deliberate export struct for stable JSON output.
Version Notes
jsonencodeandjsondecodewere introduced in MATLAB R2016b.- Modern name=value syntax such as
PrettyPrint=trueworks in R2021a and newer. readstructandwritestructgained JSON support in R2023b.readdictionarywas introduced in R2024b.
Conclusion
For most MATLAB JSON work, the core recipe is simple: jsondecode to parse, jsonencode to format, fileread when the source is a JSON file, and newer file-based helpers when you want less boilerplate. Once you know how MATLAB maps arrays, objects, null, and nonfinite numbers, most JSON interoperability issues become predictable.
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool