Why does the ordering of JSON object field names matter in the "jsondecode" function?
31 views (last 30 days)
Show older comments
MathWorks Support Team
on 11 Aug 2025 at 0:00
Answered: MathWorks Support Team
on 11 Aug 2025 at 15:41
I am using MATLAB to read JSON-formatted text using the "jsondecode" function.
For JSON-formatted text containing objects with the same field names in the same order, the "jsondecode" function will return a structure array:
>> jsondecode('[{"a": 1, "b": 2}, {"a": 3, "b": 4}]')
ans =
2×1 struct array with fields:
a
b
However, if the same field names are in a different order, the "jsondecode" function will return a cell array of scalar structures:
>> jsondecode('[{"a": 1, "b": 2}, {"b": 3, "a": 4}]')
ans =
2×1 cell array
{1×1 struct}
{1×1 struct}
What is the reason for this behavior difference and how can I work around this?
Accepted Answer
MathWorks Support Team
on 11 Aug 2025 at 0:00
The algorithm that MATLAB uses in the "jsondecode" function treats JSON arrays of objects differently depending on the field names. An array of objects with the same field names converts to a structure array in MATLAB, whereas an array of objects with different field names converts to a cell array of scalar structures. Refer to the "jsondecode" function documentation for more information.
Starting in MATLAB R2023b, the "readstruct" function can be used to work around this difference in behavior. The "readstruct" function will normalize JSON arrays of objects, consistently returning structure arrays instead of cell arrays. Refer to the "readstruct" function documentation for more information.
0 Comments
More Answers (0)
See Also
Categories
Find more on JSON Format in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!