Why Does Converting Array with Length of One to JSON Remove Array?
7 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2023-11-10
回答: MathWorks Support Team
2023-12-19
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
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 JSON Format 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!