RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact
  • License
  • Privacy

Learn

  • Docs
  • Blog
  • Benchmarks
  • RunMat vs MATLAB Online

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • jsondecode
    • jsonencode

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
valueAnyYes—Value to encode as JSON.
optionsAnyYes—Options struct with fields such as PrettyPrint and ConvertInfAndNaN.
nameStringScalarYes—Option name (for example "PrettyPrint" or "ConvertInfAndNaN").
optionValueAnyYes—Option value for the preceding option name.
nameValuePairs...AnyVariadic—Name-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
—Option value is not a scalar logical/numeric or boolean-like text.jsonencode: option value must be scalar logical or numeric
—Option name is not recognized.jsonencode: unknown option name
—Input contains NaN/Inf while ConvertInfAndNaN is false.jsonencode: ConvertInfAndNaN must be true to encode NaN or Inf values
—Input value type is not supported for JSON encoding.jsonencode: unsupported input type; expected numeric, logical, string, struct, cell, or object data
—A GPU tensor handle reaches encoding after gather pass.jsonencode: unexpected gpuArray handle after gather pass
—Internal JSON conversion or container materialization fails.jsonencode: internal conversion failed

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.
  • Automatic internal residency is gathered transparently. Explicit gpuArray input is accepted only in RunMat compatibility mode and then gathered through its owning provider.
  • All eight real integer classes serialize directly from authoritative storage to exact signed or unsigned decimal literals, including 64-bit values above flintmax.
  • Complex-number object encoding and numeric or textual coercion of logical option values are independently mode-gated RunMat extensions.

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. Automatic resident values gather transparently; admitted explicit resident values gather only after the compatibility gate. If no provider owns an admitted handle, the normal gather error is returned.

GPU memory and residency

Values placed on the device by RunMat's automatic planner gather transparently at this serialization sink. User-visible explicit gpuArray input is a RunMat-only extension; when enabled, the value gathers through the owning provider before serialization.

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?⌄

The documented MATLAB-facing surface rejects complex numeric data. RunMat compatibility mode retains an extension that encodes complex scalars as real/imag objects and complex arrays as arrays of those objects.

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.

Related Io functions

Json

jsondecode

Net

accept · read · readline · tcpclient · tcpserver · write

Repl Fs

addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · mkdir · movefile · open · opentoline · path · pathsep · pcode · pwd · readstruct · rehash · restoredefaultpath · rmdir · rmpath · run · savepath · setenv · setpref · system · tempdir · tempname · uigetdir · uigetfile · uiputfile · unsetenv · userpath · what · winqueryreg · xmlread · xmlwrite

Tabular

arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

Filetext

fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite · readlines · writelines

Archive

gunzip · gzip · unzip

Hdf5

h5disp · h5info · h5read · h5write · h5writeatt · hdf5info · hdf5read · hdf5write

Import

importdata · textscan

Mat

load · matfile · save

Http

sendmail · urldecode · urlencode · weboptions · webread · websave · webwrite

Open-source implementation

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

  • View the source for jsonencode in Rust on GitHub
  • Learn how the RunMat runtime works
  • Found a bug? Open an issue with a minimal reproduction.

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.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How jsonencode works
  • Jsonencode options
  • Does RunMat run jsonencode on the GPU?
  • GPU memory and residency
  • Examples
  • Converting a MATLAB struct to JSON
  • Serialising a matrix with pretty printing
  • Encoding nested cell arrays
  • Handling NaN and Inf values
  • Rejecting NaN when ConvertInfAndNaN is false
  • Serialising GPU-resident tensors
  • Using jsonencode with coding agents
  • FAQ
  • Related Io functions
  • Json
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Filetext
  • Archive
  • Hdf5
  • Import
  • Mat
  • Http
  • Open-source implementation
  • About RunMat