Main Content

jsonencode

Create JSON-formatted text from structured MATLAB data

Description

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

example

txt = jsonencode(data,Name,Value) encodes data using one or more name-value pair arguments.

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. 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, 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 calling jsonencode defined in SyntaxColors.

err = SyntaxColors.Error;
s = struct('Error', err);
jsonencode(s)
ans = '{"Error":{"R":1,"G":0,"B":0}}'

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

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]

Name-Value Arguments

Specify optional pairs of arguments as Name1=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)

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. A false value encodes the values as literal NaN, Infinity, or -Infinity.

Data Types: logical

Add indentation, specified as true or false. 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 with get 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 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]}}]}'

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

expand all