jsonencode

Create JSON-formatted text from structured MATLAB data

Description

example

txt = jsonencode(data) encodes data and returns a character vector in JSON format.

txt = jsonencode(data,'ConvertInfAndNaN',TF) customizes the encoding of special floating point values NaN, Inf, -Inf.

Examples

collapse all

value = {'one'; 'two'; 'three'};
jsonencode(value)
ans = 
'["one","two","three"]'

jsonencode encodes enumerations without properties as strings.

on = matlab.lang.OnOffSwitchState.on;
jsonencode(on)
ans =

    '"on"'

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)
ans =

    '"Error"'

Add a customized jsonencode function. The function must have the same signature as the MATLAB® jsonencode function, namely, a single input which is the object of the class and returning a single output which is a valid JSON string. The updated methods block is:

methods
    function c = SyntaxColors(r, g, b)  
        c.R = r; c.G = g; c.B = b;
    end
    function json = jsonencode(obj)
        s = struct('R', obj.R, 'G', obj.G, 'B', obj.B);
        json = jsonencode(s);
    end
end

Call jsonencode defined in SyntaxColors.

jsonencode(SyntaxColors.Error)
ans =

    '{"R":1,"G":0,"B":0}’

Create a struct and display the encoded value.

s = struct('Error', error);
jsonencode(s)
ans =

    '{"Error":{"R":1,"G":0,"B":0}}'

Input Arguments

collapse all

MATLAB data, specified as any supported MATLAB data type. For more information, see Limitations. For information about customizing jsonencode for enumerations, see Customize Encoded Enumerations With Properties.

Example: s.IDs = [116, 943, 234, 38793]

Customize the encoding of special floating point values NaN, Inf, and -Inf, specified as true or false. A true value encodes floating point values as null. A false value encodes the values as literal NaN, Infinity, or -Infinity.

Example: jsonencode(-Inf,'ConvertInfAndNaN',false)

Limitations

  • jsonencode does not support complex numbers or sparse arrays. Objects must have public properties encoded as name-value pairs with get methods defined on the object 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 and int32. If you encode an int32 value and then call jsondecode, the decoded value is type double.

  • 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 the newline function.

    jsonencode(['one' newline 'two'])
    ans = '"one\ntwo"'
  • To preserve other \ escape characters, consider calling sprintf on the input. Test your input to see if sprintf creates the desired result.

    jsonencode(sprintf('AB\tCD'))
    ans = '"AB\tCD"'
  • If the input contains a double quote character ", then the function inserts the \ escape character.

    jsonencode('one"two')
    ans = '"one\"two"'

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('')
'""'

<missing>

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 scalar
object scalar

Object
Object (Public properties encoded as name-value pairs.)

jsonencode(struct('a','value'))
'{"a":"value"}'

structure vector
object vector

Array of objects

jsonencode(struct('a',{true,true,false}))
'[{"a":true},{"a":true},{"a":false}]'

structure array
object 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}'

NaN
Inf

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 the features 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]}}]}'

Compatibility Considerations

expand all

Behavior changed in R2017b

Introduced in R2016b