jsonencode - Create JSON-formatted text from structured MATLAB data - MATLAB (original) (raw)
Create JSON-formatted text from structured MATLAB data
Syntax
Description
txt = jsonencode([data](#bvb7dgc-value))
encodesdata
and returns a character vector in JSON format.
txt = jsonencode([data](#bvb7dgc-value),[Name,Value](#namevaluepairarguments))
encodes data
using one or more name-value pair arguments.
Examples
Convert Cell Array of Text to JSON
value = {'one'; 'two'; 'three'}; jsonencode(value)
ans = '["one","two","three"]'
Encode Enumerations Without Properties
jsonencode
encodes enumerations without properties as strings.
on = matlab.lang.OnOffSwitchState.on; jsonencode(on)
Customize Encoded Enumerations With Properties
By default, jsonencode
encodes enumerations with properties as JSON strings. You can customize this behavior.
Create the SyntaxColors
class shown in Define Properties in Enumeration Classes with properties
and an enumeration
.
jsonencode
encodes the enumeration as a JSON string.
jsonencode(SyntaxColors.Error)
Add a customized jsonencode
function. The function must have the same signature as the MATLAB® jsonencode
function. The updatedmethods
block is:
methods
function c = SyntaxColors(r, g, b)
c.R = r; c.G = g; c.B = b;
end
function json = jsonencode(obj, varargin)
s = struct('R', obj.R, 'G', obj.G, 'B', obj.B);
json = jsonencode(s, varargin{:});
end
end
Create a struct and display the encoded value callingjsonencode
defined inSyntaxColors
.
err = SyntaxColors.Error; s = struct('Error', err); jsonencode(s)
ans = '{"Error":{"R":1,"G":0,"B":0}}'
PrettyPrint
JSON Text
Convert struct containing different data types to JSON.
s.Width = 800; s.Height = 600; s.Title = 'View from the 15th Floor'; s.Animated = false; s.IDs = [116, 943, 234, 38793]; jsonencode(s,PrettyPrint=true)
ans = '{ "Width": 800, "Height": 600, "Title": "View from the 15th Floor", "Animated": false, "IDs": [ 116, 943, 234, 38793 ] }'
Input Arguments
data
— MATLAB data
any supported MATLAB data type
MATLAB data, specified as any supported MATLAB data type. For more information, see Limitations. For information about customizingjsonencode
for enumerations, see Customize Encoded Enumerations With Properties.
Example: s.IDs = [116, 943, 234, 38793]
Name-Value Arguments
Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN
, where Name
is the argument name and Value
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name
in quotes.
Example: jsonencode(-Inf,ConvertInfAndNaN=false)
ConvertInfAndNaN
— Custom encoding
true
or1
(default) | false
or 0
Custom encoding of special floating point values NaN, Inf, and -Inf, specified as a numeric or logical 1
(true
) or 0
(false
). A true
value encodes floating point values as null
. Afalse
value encodes the values as literalNaN
, Infinity
, or-Infinity
.
Data Types: logical
PrettyPrint
— Add indentation
false
(default) | true
Add indentation, specified as true
orfalse
. MATLAB displays the JSON text with an indentation of two spaces.
Data Types: logical
Limitations
jsonencode
does not support complex numbers or sparse arrays. Objects must have public properties encoded as name-value pairs withget
methods defined on the object properties.jsonencode
does not support hidden properties.jsonencode
does not support recursive structures such as graphics objects that contain references to parent and child objects.- If you encode, then decode a value, MATLAB does not guarantee that the data type is preserved. JSON supports fewer data types than MATLAB, which results in loss of type information. For example, JSON data does not distinguish between
double
andint32
. If you encode anint32
value and then calljsondecode
, the decoded value is typedouble
. - MATLAB does not guarantee that the shape of an array is preserved. For example, a 1-by-N numeric vector is encoded as an array. If you call
jsondecode
, then MATLAB decodes the array as an N-by-1 vector.
Tips
- To preserve the newline escape character
\n
, use thenewline
function.
jsonencode(['one' newline 'two']) - To preserve other
\
escape characters, consider callingsprintf
on the input. Test your input to see ifsprintf
creates the desired result.
jsonencode(sprintf('AB\tCD')) - If the input contains a double quote character
"
, then the function inserts the\
escape character.
Algorithms
JSON supports fewer data types than MATLAB. jsonencode
converts MATLAB data types to the JSON data types listed here.
MATLAB Data Type | JSON Data Type | Example | Output |
---|---|---|---|
array, empty | Array, empty | jsonencode([])jsonencode(string.empty) | '[]' |
logical scalar | Boolean | jsonencode(true) | 'true' |
logical vector | Array of boolean | jsonencode([true,false,false]) | '[true,false,false]' |
logical array | Nested array of boolean | jsonencode(logical([0,1,0;1,1,0])) | '[[false,true,false],[true,true,false]]' |
character vector | String | jsonencode('This is a char.') | '"This is a char."' |
character array | Array of strings | jsonencode(['AC';'EG']) | '["AC","EG"]' |
string scalar | String | jsonencode("This is a string.") | '"This is a string."' |
string vector | Array of strings | jsonencode(["AC";"EG"]) | '["AC","EG"]' |
string array | Nested array of strings | jsonencode(["AC","EG";"BD","FH"]) | '[["AC","EG"],["BD","FH"]]' |
empty character vector | String | jsonencode('') | '""' |
null | jsonencode(string(nan)) | 'null' | |
numeric scalar | Number | jsonencode(2.5) | '2.5' |
numeric vector | Array of numbers | jsonencode(1:3) | '[1,2,3]' |
numeric array | Nested array of numbers | jsonencode(eye(2)) | '[[1,0],[0,1]]' |
complex numbers | Not supported | ||
table | Array of objects | Name = {'Jones';'Brown'}; Age = [40;49]; jsonencode(table(Name,Age)) | '[{"Name":"Jones","Age":40},{"Name":"Brown","Age":49}]' |
cell scalar | Array of 1 element | jsonencode({5}) | '[5]' |
cell vector | Array | jsonencode({'a',true,[2;3]}) | '["a",true,[2,3]]' |
cell array | Array flattened to a single dimension | jsonencode({1 2;3 4}) | '[1,3,2,4]' |
structure scalarobject scalar | ObjectObject (Public properties encoded as name-value pairs.) | jsonencode(struct('a','value')) | '{"a":"value"}' |
structure vectorobject vector | Array of objects | jsonencode(struct('a',{true,true,false})) | '[{"a":true},{"a":true},{"a":false}]' |
structure arrayobject array | Nested array of objects | ||
datetime scalar | String (string method used to convert date and time to string format.) | jsonencode(datetime('tomorrow')) | '"04-Nov-2016"' |
datetime vector | Array of strings | DT = datetime({'8 April 2015','9 May 2015'}, ... 'InputFormat','d MMMM yyyy'); jsonencode(DT) | '["08-Apr-2015","09-May-2015"]' |
datetime array | Nested array of strings | DT = datetime(... [{'April 2015','May 2015'};{'June 2015','July 2015'}], ... 'InputFormat','MMMM yyyy'); jsonencode(DT) | '[["01-Apr-2015","01-May-2015"], ["01-Jun-2015","01-Jul-2015"]]' |
categorical scalar | String (string method used to create string format.) | jsonencode(categorical({'r'})) | '"r"' |
categorical vector | Array of strings | jsonencode(categorical({'r';'g';'b'})) | '["r","g","b"]' |
categorical array | Nested array of strings | jsonencode(categorical( ... {'r' 'b' 'g'; ... 'g' 'r' 'b'; ... 'b' 'r' 'g'})) | '[["r","b","g"],["g","r","b"],["b","r","g"]]' |
containers.Map | Object | jsonencode(containers.Map( ... {'Jan','Feb','Mar'}, ... [327,368,197])) | '{"Feb":368,"Jan":327,"Mar":197}' |
NaNInf | null | jsonencode([1,2,NaN,3,Inf]) | '[1,2,null,3,null]' |
enumeration | String | jsonencode(matlab.lang.OnOffSwitchState.on) | '"on"' |
To pass a scalar MATLAB object as a scalar JSON array (enclosed in []
characters), convert the object using the cell array construction operator{}
. For example, the following code converts the value of thefeatures
field into a scalar JSON array.
S = struct("features", struct("type", "Feature", "geometry",... struct("type", "point", "coordinates", [-105, 40]))); S.features = {S.features}; s = jsonencode(S)
s = '{"features":[{"type":"Feature","geometry":{"type":"point","coordinates":[-105,40]}}]}'
Extended Capabilities
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
Version History
Introduced in R2016b
R2021a: Update customized jsonencode
for MATLAB classes
Starting in R2021a, the jsonencode
function accepts variable input arguments. If you customize the jsonencode
function for your MATLAB classes, then update the calling syntax by replacing:
function json = jsonencode(obj)
with:
function json = jsonencode(obj,varargin)
For an example, see Customize JSON Encoding for MATLAB Classes.
R2017b: Encode NaN and Inf as null
The jsonencode
function encodes MATLAB NaN and Inf values in JSON as null.
In R2017a and earlier, the function encodes NaN as 'NaN'
and Inf as 'Inf'
. To continue encoding NaN as'NaN'
or Inf as 'Inf'
, calljsonencode
with the 'ConvertInfAndNaN'
option set to false
. For example,
jsonencode(NaN,'ConvertInfAndNaN',false)