RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.2, Nov 26, 2026 ·

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 JSON text in RunMat.

jsonencode(value) serializes supported numeric, logical, character, string, struct, cell, and object values to a character row containing JSON text. Options control indentation and non-finite numbers.

Syntax

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

Inputs

value
Type
Any
Required
Yes
Description
Value to encode as JSON.
options
Type
Any
Required
Yes
Description
Options struct with fields such as PrettyPrint and ConvertInfAndNaN.
name
Type
StringScalar
Required
Yes
Description
Option name (for example "PrettyPrint" or "ConvertInfAndNaN").
optionValue
Type
Any
Required
Yes
Description
Option value for the preceding option name.
nameValuePairs...
Type
Any
Required
Variadic
Description
Name-value option pairs.
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

jsonText
Type
Any
Description
JSON text encoded as a character row vector.
NameTypeDescription
jsonTextAnyJSON text encoded as a character row vector.

Errors

—
When
Single options argument is provided but is not a struct.
Message
jsonencode: expected name/value pairs or options struct
—
When
Name-value options do not come in pairs.
Message
jsonencode: name/value pairs must come in pairs
—
When
Option name is not a character vector or string scalar.
Message
jsonencode: option names must be character vectors or strings
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

Values and layout

The result is a 1-by-N character row, not a string scalar. Numeric and logical arrays become JSON arrays in logical row/column order from column-major storage; scalars become bare literals. Character and string values become strings or arrays of strings according to their shape.

Struct scalars become objects and struct arrays become arrays of objects. Object keys are emitted in canonical lexical order. Empty struct arrays become [] and cannot retain their field schema in JSON. Cell arrays preserve nested rows and columns as JSON arrays.

All eight real integer classes serialize exact signed or unsigned decimal literals directly from their integer storage, including uint64 values above flintmax. Complex object encoding and sparse densification are separate RunMat-only extensions.

Options and non-finite values

By default PrettyPrint is false and ConvertInfAndNaN is true, so NaN and positive or negative infinity become null. With ConvertInfAndNaN false, encountering a non-finite value raises an error. PrettyPrint true uses four-space indentation and LF newlines.

Pass a scalar options struct or complete name-value pairs. Supported names are PrettyPrint and ConvertInfAndNaN, case-insensitively. Logical values are the compatible option form. Floating numeric, typed-integer, and boolean-like text coercions are separately gated RunMat extensions; a documented 0 or 1 numeric ConvertInfAndNaN value remains accepted. Invalid names, pair counts, and known extension gates are checked before resident data gather.

Residency and portability

No GPU JSON kernel runs. Automatic internal residency gathers through the owning provider; explicit gpuArray values require the RunMat resident-input extension before gather. Missing owners return the normal gather failure. Native and browser runtimes share the host serializer.

Printable Unicode is emitted directly; quotes and control characters use standard JSON escapes. Serialization builds an intermediate JSON tree and result character row, so large nested values can require substantial host memory.

Examples

Convert a struct to JSON

record = struct('name', 'entry', 'age', 37);
encoded = jsonencode(record)

Expected output:

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

Pretty-print a matrix

A = [8 1 6; 3 5 7; 4 9 2];
encoded = jsonencode(A, 'PrettyPrint', true)

Expected output:

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

Encode nested cells

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

Expected output:

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

Convert NaN and Inf to null

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

Expected output:

encoded = '[1,null,null]'

Reject non-finite values when conversion is disabled

data = [1 NaN Inf];
try
  jsonencode(data, 'ConvertInfAndNaN', false);
catch err
  message = err.message;
  disp(message);
end

Expected output:

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

Serialize GPU-resident data

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 values are supported?⌄

Numeric, logical, character, string, struct, cell, and supported object values. Opaque foreign values and function handles reject.

Why are fields alphabetic?⌄

JSON object keys use deterministic lexical order rather than runtime insertion order.

How are complex numbers encoded?⌄

The compatible surface rejects them; RunMat mode has a separately gated real/imag object extension.

Does the result use char or string?⌄

A row character array. Use string(jsonencode(x)) if a string scalar is wanted.

Can nested values be pretty-printed?⌄

Yes, with PrettyPrint true; indentation uses four spaces per level.

How do empty arrays encode?⌄

Empty numeric, logical, and string arrays become []; a zero-row character array also becomes [], while a 1-by-0 character row becomes an empty JSON string. Scalar empty structs become {}, while empty struct arrays become [].

Is column-major layout preserved?⌄

The JSON uses logical row/column order; decoding a rectangular result reconstructs the corresponding RunMat shape.

What if ConvertInfAndNaN is false?⌄

Any NaN, Inf, or -Inf raises an error instead of emitting null.

Which newline style is used?⌄

Pretty-printed output uses LF on every platform.

Are Unicode characters escaped?⌄

Printable Unicode is emitted directly. Quotes and control characters use JSON escapes.

Related Io functions

Json

jsondecode

Net

accept · read · readline · tcpclient · tcpserver · write

Repl Fs

addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · filesep · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · memmapfile.subsasgn · memmapfile.subsref · 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 · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite

Audio

audioinfo · audioread

Io

clc · diary · disp · display · format · input

Data

commit · data.copy · data.create · data.delete · data.exists · data.export · data.import · data.inspect · data.list · data.move · data.open · DataArray.chunk_shape · DataArray.codec · DataArray.dtype · DataArray.fill · DataArray.name · DataArray.rank · DataArray.read · DataArray.resize · DataArray.shape · DataArray.write · Dataset.array · Dataset.arrays · Dataset.attrs · Dataset.begin · Dataset.get_attr · Dataset.has_array · Dataset.id · Dataset.path · Dataset.refresh · Dataset.set_attr · Dataset.set_attrs · Dataset.snapshot · Dataset.version · DataTransaction.abort · DataTransaction.commit · DataTransaction.create_array · DataTransaction.delete_array · DataTransaction.fill · DataTransaction.id · DataTransaction.resize · DataTransaction.set_attr · DataTransaction.set_attrs · DataTransaction.status · DataTransaction.write

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 · matlab.io.MatFile.subsasgn · matlab.io.MatFile.subsref · save

Http

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

Source you can read

Every RunMat function's source is public. 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 a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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
  • Values and layout
  • Options and non-finite values
  • Residency and portability
  • Examples
  • Convert a struct to JSON
  • Pretty-print a matrix
  • Encode nested cells
  • Convert NaN and Inf to null
  • Reject non-finite values when conversion is disabled
  • Serialize GPU-resident data
  • Using jsonencode with coding agents
  • FAQ
  • Related Io functions
  • Json
  • Net
  • Repl Fs
  • Tabular
  • Audio
  • Io
  • Data
  • Filetext
  • Archive
  • Hdf5
  • Import
  • Mat
  • Http
  • Source you can read
  • About RunMat