Why does the ordering of JSON object field names matter in the "jsondecode" function?

31 vues (au cours des 30 derniers jours)
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?

Réponse acceptée

MathWorks Support Team
MathWorks Support Team le 11 Août 2025 à 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.

Plus de réponses (0)

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by