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

JSON (JavaScript Object Notation) has become the de facto standard for data interchange on the web and in many modern applications. Whether you're working with REST APIs, configuration files, or saving complex data structures, dealing with JSON is a common task. Fortunately, MATLAB provides powerful, built-in functions to seamlessly convert between MATLAB data types and JSON strings: jsonencode and jsondecode.

Why JSON in MATLAB?

MATLAB is widely used for data analysis, simulation, and algorithm development. Interacting with external systems, web services, or saving/loading data in a human-readable, portable format often requires JSON. MATLAB's built-in functions make this process straightforward, eliminating the need for external libraries or manual parsing.

jsonencode: Encoding MATLAB Data to JSON

The jsonencode function converts a MATLAB data structure (like a scalar, array, cell array, or struct) into a JSON-formatted string.

Basic Usage

The simplest use is converting a scalar or a struct:

Example: Encoding a Struct


% Create a simple MATLAB struct
person.name = 'Alice';
person.age = 30;
person.isStudent = false;

% Encode the struct to a JSON string
jsonString = jsonencode(person);

% Display the resulting JSON string
disp(jsonString);

Expected Output: {"name":"Alice","age":30,"isStudent":false}

Handling Data Types

jsonencode automatically handles various MATLAB data types and maps them to their corresponding JSON types:

  • Numeric arrays (double, single, int, etc.) become JSON arrays of numbers.
  • Character arrays (strings) become JSON strings.
  • Logical scalars (true, false) become JSON booleans (true, false).
  • Structs become JSON objects. Field names become keys.
  • Cell arrays become JSON arrays.
  • Empty arrays ([]) become JSON arrays ([]).
  • NaN and Inf values in numeric arrays are encoded as null (since JSON doesn't have standard representations for these).
  • missing values are encoded as null.

Example: Encoding Mixed Data Types


% Data structure with various types
data.numbers = [1, 2.5, NaN];
data.names = {'Bob', 'Charlie'};
data.isActive = true;
data.description = "A test object";
data.emptyList = [];

jsonString = jsonencode(data);
disp(jsonString);

Expected Output (approximate): {"numbers":[1,2.5,null],"names":["Bob","Charlie"],"isActive":true,"description":"A test object","emptyList":[]}

Formatting Options (Pretty-Printing)

By default, jsonencode produces a compact JSON string with no whitespace. For readability, especially when saving to a file or debugging, you can use the 'PrettyPrint' option:

Example: Using PrettyPrint


person.name = 'Alice';
person.age = 30;
person.city = 'New York';

% Encode with pretty-printing
jsonStringPretty = jsonencode(person, 'PrettyPrint', true);

% Display the pretty-printed JSON string
disp(jsonStringPretty);

Expected Output (formatted):

{
  "name": "Alice",
  "age": 30,
  "city": "New York"
}

jsondecode: Decoding JSON to MATLAB Data

The jsondecode function takes a JSON-formatted string and converts it back into a corresponding MATLAB data structure.

Basic Usage

Simply pass the JSON string to the function:

Example: Decoding a JSON Object


% A JSON string representing an object
jsonString = '{"name":"Alice","age":30,"isStudent":false}';

% Decode the JSON string into a MATLAB struct
matlabData = jsondecode(jsonString);

% Display the resulting MATLAB struct
disp(matlabData);

Expected Output:

  name: 'Alice'
   age: 30
isStudent: 0

Note: JSON true/false decode to MATLAB logical 1/0.

Mapping JSON Types to MATLAB

jsondecode performs the reverse mapping of jsonencode:

  • JSON objects become MATLAB structs. Keys become field names. If a key is not a valid MATLAB identifier, it may be modified or require dynamic field access.
  • JSON arrays become MATLAB cell arrays if elements have different types, or numeric/logical arrays if elements are homogeneous numbers or booleans.
  • JSON strings become MATLAB character vectors (strings).
  • JSON numbers become MATLAB double scalars or arrays.
  • JSON booleans (true, false) become MATLAB logical scalars (1, 0).
  • JSON null becomes a MATLAB empty array ([]).

Example: Decoding a JSON Array


% A JSON string representing an array with mixed types
jsonString = '["apple", 123, true, null, [1, 2]]';

% Decode the JSON string into a MATLAB cell array
matlabData = jsondecode(jsonString);

% Display the resulting MATLAB cell array
disp(matlabData);

Expected Output:

    'apple'    [  123]    [1x1 logical]    []    [1x2 double]

Note: The output shows a cell array containing a string, a numeric scalar, a logical scalar (1), an empty numeric array, and a numeric array.

Handling Invalid JSON

If jsondecode encounters invalid JSON syntax, it will throw an error. You should use try-catch blocks to handle potential decoding errors gracefully, especially when dealing with external data sources.

Common Scenarios & Best Practices

Working with JSON Files

You can easily read JSON from a file, decode it, work with the data, and then encode it back to a file.

Example: Read, Modify, and Write JSON File


% --- Step 1: Write initial JSON to a file ---
initialData.version = 1.0;
initialData.settings.mode = 'auto';
initialData.settings.level = 5;

jsonStringToFile = jsonencode(initialData, 'PrettyPrint', true);

% Define filename (use fullpath or navigate)
filename = 'my_config.json';

% Open file for writing, write content, close file
fid = fopen(filename, 'w');
fprintf(fid, '%s', jsonStringToFile);
fclose(fid);
disp(['Wrote initial JSON to ' filename]);

% --- Step 2: Read JSON from the file ---
disp(['Reading JSON from ' filename]);
fid = fopen(filename, 'r');
% Read entire file as a single string. Note: fscanf might stop at whitespace,
% a better approach for reading the whole file is often fileread (R2014b+)
% rawText = fscanf(fid, '%s'); % Original line - might fail on whitespace
rawText = fread(fid, '*char')'; % Alternative: Read all bytes as chars
fclose(fid);

% Decode the JSON string
readData = jsondecode(rawText);
disp('Decoded Data:');
disp(readData);

% --- Step 3: Modify the data ---
readData.settings.mode = 'manual';
readData.notes = 'Updated setting';
disp('Modified Data:');
disp(readData);

% --- Step 4: Encode modified data and write back to file ---
modifiedJsonString = jsonencode(readData, 'PrettyPrint', true);

fid = fopen(filename, 'w'); % Overwrite the file
fprintf(fid, '%s', modifiedJsonString);
fclose(fid);
disp(['Wrote modified JSON back to ' filename]);

This example demonstrates the full cycle of working with JSON files in MATLAB. Note: The original fscanf(fid, '%s') might stop reading at whitespace; using fileread(filename) (R2014b+) or fread(fid, '*char')' is generally more reliable for reading the entire file content including spaces and newlines typically found in pretty-printed JSON. I've updated the example to use fread.

Potential Pitfalls and Considerations

  • Data Type Conversion: Be mindful of how specific MATLAB types (like dates, times, categorical arrays) are handled. They might not have a direct JSON equivalent and could be converted to strings or numbers in a way that requires specific handling on the decoding side.
  • Large Data: For extremely large datasets, converting the entire structure to a single string might be memory-intensive. Consider streaming or processing data in chunks if possible, although jsonencode/jsondecode are generally optimized.
  • Non-Standard JSON: MATLAB's functions strictly follow the JSON standard. They will reject invalid JSON (e.g., trailing commas, comments, unquoted keys). If you're consuming data that might contain such non-standard elements, you might need pre-processing or a different parsing library.
  • Object Encoding/Decoding: By default, jsonencode encodes public properties of MATLAB objects. For more complex object serialization (e.g., including private/protected properties, or custom representations), you might need to implement custom toJSON or similar methods within your object classes (consult MATLAB documentation for advanced serialization).
  • Field Names: MATLAB struct field names must be valid MATLAB identifiers. JSON keys can be any string. jsondecode attempts to create valid field names, but this can sometimes lead to unexpected results if keys are complex. Using the 'SwitchFieldName' option in jsondecode can provide more control.

Conclusion

MATLAB's jsonencode and jsondecode functions provide a robust and convenient way to interact with JSON data directly within your MATLAB workflows. Understanding the data type mappings and utilizing options like 'PrettyPrint' will help you effectively integrate MATLAB with external systems and data formats that rely on JSON.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool