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 Center および File ExchangeJSON Format についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by