MATLAB: Decode JSON into only struct array

json decodestruct array

Hi,
I am using jsondecode function in matlab to decode nested json script. I want the final output in struct array only. When some child keys are missing, I get a cell array. However, I would like to have all the keys in struct array and if it the child key is not present, I want that key with empty value. Is this function foreseen to have this functionality? is there any fast alternaive to achieve it?
Thanks

Best Answer

jsondecode is certainly never going to convert a json array into a structure array as there's no guarantee that the objects in the array are of the same type. In your example, the two structures created don't have the same fields.
You can of course, write your own function that merges structures with different fields, filling the missing fields with [] or '' or whatever:
function structarray = mergedissimilarstructures(structures, defaultempty)
%structures: a cell array of scalar structures to merge
%defaultempy: the value to use to fill missing fields. Optional, default = []
%structarray: a structure array the same size as the input structures cell array.
% The fields of structurarray is the union of the fields of the input structures
%TODO: input validation
if nargin < 2
defaultempty = [];
end
fieldunion = cellfun(@fieldnames, structures, 'UniformOutput', false);
fieldunion = unique(vertcat(fieldunion{:}));
structarray = repmat({defaultempty}, numel(structures), numel(fieldunion));
for sidx = 1:numel(structures)
[~, destcol] = ismember(fieldnames(structures{sidx}), fieldunion);
structarray(sidx, destcol) = struct2cell(structures{sidx});
end
structarray = reshape(cell2struct(structarray, fieldunion, 2), size(structures));
end