Create JSON-formatted text from structured MATLAB data (2024)

Create JSON-formatted text from structured MATLAB data

collapse all in page


txt =jsonencode(data)

txt = jsonencode(data,Name,Value)



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

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


collapse all

Convert Cell Array of Text to JSON

Open Live Script

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)
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.

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{:}); endend

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}}'

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

collapse all

dataMATLAB data
any supported MATLAB data type

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)

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

Data Types: logical

PrettyPrintAdd indentation
false (default) | true

Add indentation, specified as true or false. MATLAB displays the JSON text with an indentation of two spaces.

Data Types: logical


  • 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 doesnot support recursive structures such as graphics objects that contain referencesto parent and child objects.

  • If you encode, then decode a value, MATLAB doesnot guarantee that the data type is preserved. JSON supports fewerdata 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 doesnot 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.


  • 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.

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

    ans = '"one\"two"'


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



array, empty

Array, empty


logical scalar



logical vector

Array of boolean


logical array

Nested array of boolean


character vector


jsonencode('This is a char.')
'"This is a char."'

character array

Array of strings


string scalar


jsonencode("This is a string.")
'"This is a string."'

string vector

Array of strings


string array

Nested array of strings


empty character vector






numeric scalar



numeric vector

Array of numbers


numeric array

Nested array of numbers


complex numbers

Not supported


Array of objects

Name = {'Jones';'Brown'};Age = [40;49];jsonencode(table(Name,Age))

cell scalar

Array of 1 element


cell vector



cell array

Array flattened to a single dimension

jsonencode({1 2;3 4})

structure scalar
object scalar

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


structure vector
object vector

Array of objects


structure array
object array

Nested array of objects

datetime scalar

String (string method used to convertdate and time to string format.)


datetime vector

Array of strings

DT = datetime({'8 April 2015','9 May 2015'}, ... 'InputFormat','d MMMM yyyy');jsonencode(DT)

datetime array

Nested array of strings

DT = datetime(... [{'April 2015','May 2015'};{'June 2015','July 2015'}], ... 'InputFormat','MMMM yyyy');jsonencode(DT)

categorical scalar

String (string method used to createstring format.)


categorical vector

Array of strings


categorical array

Nested array of strings

jsonencode(categorical( ... {'r' 'b' 'g'; ... 'g' 'r' 'b'; ... 'b' 'r' 'g'}))



jsonencode(containers.Map( ... {'Jan','Feb','Mar'}, ... [327,368,197]))







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

See Also

jsondecode | webwrite

MATLAB Command

You clicked a link that corresponds to this MATLAB command:


Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Create JSON-formatted text from structured MATLAB data (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:


  • América Latina (Español)
  • Canada (English)
  • United States (English)


  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

Contact your local office

Create JSON-formatted text from structured MATLAB data (2024)
Top Articles
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 6088

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.