Why Does Converting Array with Length of One to JSON Remove Array?

7 views (last 30 days)
When using 'jsonencode' to convert a struct to JSON, arrays of size one are not converted as arrays.
The following example is an array of size two being converted to JSON correctly:
>> jsonencode(struct('test', [string('1'), string('2')]))
The output is: {"test":["1","2"]}
The following example shows what happens when the array is of size one:
>> jsonencode(struct('test', [string('1')]))
The output is: {"test": "1"}
The desired output is: {"test": ["1"]}
How do I achieve this result?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 10 Nov 2023
In MATLAB, there is not a distinction between a single element string array and a string scalar. The following code snippet shows this case:
>> a = [string("s")]
a =
"s"
>> b = string("s")
b =
"s"
>> isscalar(a)
ans =
logical
1
>> isscalar(b)
ans =
logical
1
A single element array is considered scalar. Therefore, when converting to JSON, there is not a way to distinguish the two cases.
Using cell arrays instead will result in the desired output. The following code illustrates this workflow:
s.a = {"a"}
s.b = {"b1", "b2"}
jsonencode(s)
ans =
'{"a":["a"],"b":["b1","b2"]}'

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!