FUNCTION REFERENCE

jsonencode

Encode a value as JSON text.

Encode a value as JSON text.

Syntax

txt = jsonencode(v)

Syntax

txt = jsonencode(v, 'PrettyPrint', true)

Syntax

txt = jsonencode(v, 'ConvertInfAndNaN', false)

Returns a character vector. Numeric and logical scalars become numbers and true/false, vectors become flat JSON arrays, matrices become arrays of rows and N-D arrays arrays nested by dimension. Character vectors and string scalars become JSON strings (a missing string becomes null, a char matrix an array of row strings). A cell array becomes a JSON array of its elements in column order, a scalar struct an object, a struct array an array of objects and a containers.Map an object of its keys and values. Empty arrays, cells and structs become []. NaN and Inf become null unless 'ConvertInfAndNaN' is false, which writes NaN, Infinity and -Infinity. 'PrettyPrint', true adds line breaks and two-space indentation.

Example

jsonencode(struct('a',[1 2 3],'b','text'))   % '{"a":[1,2,3],"b":"text"}'

Example

jsonencode({1, true, 'x', []})   % '[1,true,"x",[]]'

Example

jsonencode([1 NaN Inf])   % '[1,null,null]'

Example

jsonencode(magic(3), 'PrettyPrint', true)

Differences from MATLAB: Numbers use the shortest text that reads back exactly, with exponent form (1e+300 is written 1e300) outside 1e-5 to 1e15. Complex values, function handles, graphics handles and other objects are errors. N-D input must sit inside a struct or cell field; an N-D array passed directly is rejected. The result is a character vector, so it can hold at most 65536 characters.

These are the engine’s help pages. Each page keeps its compatibility notes. File operations are unavailable in the browser.