Why Does Converting Array with Length of One to JSON Remove Array?
7 views (last 30 days)
Show older comments
MathWorks Support Team
on 10 Nov 2023
Answered: MathWorks Support Team
on 19 Dec 2023
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
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"]}'
0 Comments
More Answers (0)
See Also
Categories
Find more on JSON Format in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!