readstruct json seems to wrongly combine structs into a vector

4 Ansichten (letzte 30 Tage)
Adam
Adam am 18 Sep. 2024
Bearbeitet: Adam am 20 Sep. 2024
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 Kommentare
Stephen23
Stephen23 am 18 Sep. 2024
Bearbeitet: Stephen23 am 19 Sep. 2024
"Is this a bug?"
Not a bug.
It is documented in the section entitled "Get Information on Elements in Nonuniform Structure":
Adam
Adam am 19 Sep. 2024
Thanks for pointing this out

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam
Adam am 20 Sep. 2024
Bearbeitet: Adam am 20 Sep. 2024
Stephen23's comment on the original question contains the correct answer to the question: it's not a bug, but a well documented feature.
I wrote this small function to "fix" my struct vectors. Maybe it could be useful for other people stumbling onto this question
function data = fix_struct_vectors(data)
% this function recurses through a data structure and
% + casts all struct vectors to cell arrays
% + removes all struct fields for which values are <missing>
if isstruct(data)
if ~isscalar(data)
data = num2cell(data);
data = fix_struct_vectors(data);
return
end
for field = string(fieldnames(data))'
val = data.(field);
if ismissing(val)
data = rmfield(data,field);
else
data.(field) = fix_struct_vectors(val);
end
end
elseif iscell(data)
for ind = 1 : numel(data)
data{ind} = fix_struct_vectors(data{ind});
end
end
end

Weitere Antworten (1)

Vandit
Vandit am 18 Sep. 2024
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.

Produkte


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by