Why does the ordering of JSON object field names matter in the "jsondecode" function?
조회 수: 11 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2025년 8월 11일
답변: MathWorks Support Team
2025년 8월 11일
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?
채택된 답변
MathWorks Support Team
2025년 8월 11일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 JSON Format에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!