RunMat
GitHub

jsonencode — Serialize MATLAB values to UTF-8 JSON text with MATLAB-compatible defaults.

Convert NaN, Inf, -Inf to null. Set false to raise an error when these values are encountered.

How jsonencode works in 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.

How jsonencode runs on the GPU

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 memory and residency

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.

Examples

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]]'

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.

These functions work well alongside jsonencode. Each page has runnable examples you can try in the browser.

jsondecode, gpuArray, gather

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how jsonencode works, line by line, in Rust.

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code — faster, on any GPU, with no license required.

  • Simulations that took hours now take minutes. RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed.
  • Start running code in seconds. Open the browser sandbox or download a single binary. No license server, no IT ticket, no setup.
  • A full development environment. GPU-accelerated 2D and 3D plotting, automatic versioning on every save, and a browser IDE you can share with a link.

Getting started · Benchmarks · Pricing

Try RunMat — free, no sign-up

Start running MATLAB code immediately in your browser.