RunMat
GitHub

jsonencode — Serialize MATLAB values to UTF-8 JSON text in RunMat.

jsonencode(value) serializes MATLAB values to UTF-8 JSON text. NaN/Inf handling, field ordering, and scalar/array encoding behavior follow MATLAB-compatible defaults in RunMat.

Syntax

jsonText = jsonencode(value)
jsonText = jsonencode(value, options)
jsonText = jsonencode(value, name, optionValue)
jsonText = jsonencode(value, nameValuePairs...)

Inputs

NameTypeRequiredDefaultDescription
valueAnyYesValue to encode as JSON.
optionsAnyYesOptions struct with fields such as PrettyPrint and ConvertInfAndNaN.
nameStringScalarYesOption name (for example "PrettyPrint" or "ConvertInfAndNaN").
optionValueAnyYesOption value for the preceding option name.
nameValuePairs...AnyVariadicName-value option pairs.

Returns

NameTypeDescription
jsonTextStringScalarJSON text encoded as a character row vector.

Errors

IdentifierWhenMessage
Single options argument is provided but is not a struct.jsonencode: expected name/value pairs or options struct
Name-value options do not come in pairs.jsonencode: name/value pairs must come in pairs
Option name is not a character vector or string scalar.jsonencode: option names must be character vectors or strings

How jsonencode works

  • 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.

Does RunMat run jsonencode 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]]'

Using jsonencode with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how jsonencode changes the result.

Run a small jsonencode example, explain the result, then change one input and compare the output.

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.

Open-source implementation

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

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.

  • RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
  • Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.