Why does the ordering of JSON object field names matter in the "jsondecode" function?
31 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 11 de Ag. de 2025 a las 0:00
Respondida: MathWorks Support Team
el 11 de Ag. de 2025 a las 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?
Respuesta aceptada
MathWorks Support Team
el 11 de Ag. de 2025 a las 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre JSON Format en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!