readstruct json seems to wrongly combine structs into a vector
4 次查看(过去 30 天)
显示 更早的评论
I was reading the following json file with the readstruct function:
{
"demo": [
{
"field1": 198.0,
"field2": 70.0,
},
{
"field3": 1024,
}
]
}
and, to my surprise, I am not getting a cell array with structs, but a struct vector:
>> d = readstruct("demo.json")
d =
struct with fields:
demo: [1×2 struct]
where each of the elements in the struct vector has the following fields:
>> d.demo(1)
ans =
struct with fields:
field1: 198
field2: 70
field3: <missing>
>> d.demo(2)
ans =
struct with fields:
field1: <missing>
field2: <missing>
field3: 1024
Is this a bug? I would expect the import to return a cell array here.
2 个评论
采纳的回答
更多回答(1 个)
Vandit
2024-9-18
Hello Adam,
No, this is not a bug. The "readstruct" function in MATLAB reads a JSON file and returns a struct array. In your case, the JSON file contains an array of objects, so it is imported as a struct array. Each element in the struct array corresponds to an object in the JSON array.
If you want to convert the struct array into a cell array of structs, you can use the "struct2cell" function. Here's an example:
cellArray = struct2cell(d.demo)
This will give you a cell array where each cell contains a struct with the fields 'field1', 'field2', and 'field3'.
For more information on "readstruct" and "struct2cell" functions, please refer to the following documentations:
Hope this helps.
另请参阅
类别
在 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!