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.
Returns
jsonText- Type
Any- Description
- JSON 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
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);
endExpected output:
jsonencode: ConvertInfAndNaN must be true to encode NaN or Inf valuesSerialize 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
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
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
Import
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.