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

조회 수: 7 (최근 30일)
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?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2023년 11월 10일
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개)

카테고리

Help CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by