View all functions

CategoryIo: Json
GPUYes

What does the jsonencode function do in MATLAB / RunMat?

jsonencode converts MATLAB values into UTF-8 JSON text. The builtin mirrors MATLAB defaults: scalars become numbers or strings, matrices turn into JSON arrays, structs map to JSON objects, and NaN/Inf values encode as null unless you disable the conversion.

How does the jsonencode function behave in MATLAB / RunMat?

  • Returns a 1×N character array containing UTF-8 encoded JSON text.
  • Numeric and logical arrays become JSON arrays, preserving MATLAB column-major ordering.
  • Scalars encode as bare numbers/strings rather than single-element arrays.
  • Struct scalars become JSON objects; struct arrays become JSON arrays of objects.
  • Cell arrays map to JSON arrays, with nested arrays when the cell is 2-D.
  • String arrays and char arrays become JSON strings (1 element) or arrays of strings (multiple rows).
  • By default, NaN, Inf, and -Inf values encode as null. Set 'ConvertInfAndNaN' to false to raise an error instead.
  • Pretty printing is disabled by default; enable it with the 'PrettyPrint' option.
  • Inputs that reside on the GPU are gathered back to host memory automatically.

jsonencode Options

NameTypeDefaultDescription
PrettyPrintlogicalfalseEmit indented, multi-line JSON output.
ConvertInfAndNaNlogicaltrueConvert NaN, Inf, -Inf to null. Set false to raise an error when these values are encountered.

Examples of using the jsonencode function in MATLAB / RunMat

Converting a MATLAB struct to JSON

person = struct('name', 'Ada', 'age', 37);
encoded = jsonencode(person);

Expected output:

encoded = '{"age":37,"name":"Ada"}'

Serialising a matrix with pretty printing

A = magic(3);
encoded = jsonencode(A, 'PrettyPrint', true);

Expected output:

encoded =
'[
    [8,1,6],
    [3,5,7],
    [4,9,2]
]'

Encoding nested cell arrays

C = {struct('task','encode','ok',true), {'nested', 42}};
encoded = jsonencode(C);

Expected output:

encoded = '[{"ok":true,"task":"encode"},["nested",42]]'

Handling NaN and Inf values

data = [1 NaN Inf];
encoded = jsonencode(data);

Expected output:

encoded = '[1,null,null]'

Rejecting NaN when ConvertInfAndNaN is false

try
    jsonencode(data, 'ConvertInfAndNaN', false);
catch err
    disp(err.message);
end

Expected output:

jsonencode: ConvertInfAndNaN must be true to encode NaN or Inf values

Serialising GPU-resident tensors

G = gpuArray(eye(2));
encoded = jsonencode(G);

Expected output:

encoded = '[[1,0],[0,1]]'

jsonencode Function GPU Execution Behaviour

jsonencode never launches GPU kernels. When the input contains gpuArray data, RunMat gathers those values back to host memory via the active acceleration provider and then serialises on the CPU. If no provider is registered, the builtin propagates the same gather error used by other residency sinks (gather: no acceleration provider registered).

GPU residency in RunMat (Do I need gpuArray?)

For most workflows you do not need to call gpuArray explicitly before using jsonencode. The auto-offload planner and fusion system keep track of residency, so any GPU-backed tensors that flow into jsonencode are gathered automatically as part of this sink operation. If you prefer to control residency manually—or need MATLAB parity—you can still wrap data with gpuArray and call gather explicitly before serialising.

FAQ

What MATLAB types does jsonencode support?

Numeric, logical, string, char, struct, cell, and table-like structs are supported. Unsupported types such as function handles or opaque objects raise an error.

Why are my field names sorted alphabetically?

RunMat sorts struct field names to produce deterministic JSON (matching MATLAB when fields are stored as scalar structs).

How are complex numbers encoded?

Complex scalars become objects with real and imag fields. Complex arrays become arrays of those objects, mirroring MATLAB.

Does jsonencode return a character array or string?

It returns a row character array (char) for MATLAB compatibility. Use string(jsonencode(x)) if you prefer string scalars.

Can I pretty-print nested structures?

Yes. Pass 'PrettyPrint', true to jsonencode. Indentation uses four spaces per nesting level, just like MATLAB's pretty-print mode.

How are empty arrays encoded?

Empty numeric, logical, char, and string arrays become []. Empty structs become {} if scalar, or [] if they are empty arrays of structs.

Does jsonencode preserve MATLAB column-major ordering?

Yes. Arrays are emitted in MATLAB's logical row/column order, so reshaping on decode reproduces the original layout.

What happens when ConvertInfAndNaN is false?

Encountering NaN, Inf, or -Inf raises jsonencode: ConvertInfAndNaN must be true to encode NaN or Inf values.

How do I control the newline style?

jsonencode always emits \n (LF) line endings when PrettyPrint is enabled, regardless of platform, matching MATLAB's behaviour.

Are Unicode characters escaped?

Printable Unicode characters are emitted verbatim. Control characters and quotes are escaped using standard JSON escape sequences.

See Also

jsondecode, gpuArray, gather

Source & Feedback