I am attempting to use the jsondecode function to look at weather data via an API. The issue I am running into is that the format of data type in Matlab changes depending on what is returned.
For example, if I am look at 5 days, and all 5 days have the same information (such as Temperature, wind speed, humidity, and chance of precipitation), then Matlab will format the data as a structure array. So then I access individual values using smooth parentheses ( ).
However, if one of the days is different, then Matlab will format the data as a cell array of scalar structures. Say that it happened to rain one day, then it might add the field "precipitation type". Now since one day is different, I must access the data using curly braces { }.
Is there any way to avoid this? Or force it to use certain formatting all the time? (Such as always returning it as always using a cell array format?)

답변 (1개)

Carl
Carl 2017년 4월 4일

0 개 추천

Unfortunately, there doesn't seem to be a way to force the output to be a specific format. As a workaround, I'd suggest checking the output with the 'iscell' function, and then work with the data accordingly.

댓글 수: 4

Peter
Peter 2020년 6월 12일
I don't have a solution either, but run into the same issue that sometimes some components of the decoded json seem to be cells, and othertimes are arrays, even though the structure of the returned json bundle is the same (the contents is different, but the data model/structure to how the data is organized in the json bundle is the same).
I've too been forced to using the kludgy workaround of using if statements like " if iscell ....." . It makes code unnecessarily complex unfortunately.
Peter
Peter 2020년 6월 12일
I'll also add that the behavior changes over versions of MATLAB. In R20xxx the same json bundle might have some decoded elements returned as cells, but in another version, the exact same json bundle might have the same elements returned as a double.
Very frustrating.
Doug Addy
Doug Addy 2020년 9월 21일
Very frustrating indeed, this is a very common situation where json data has optional fields. Please just return objects in a cell array, having to handle each case separately with exactly the same code with different brackets is really silly.
Jidong Zhang
Jidong Zhang 2022년 7월 28일
편집: Jidong Zhang 2022년 7월 28일
I came across exactly the same situation and I completely agree with Doug. Please help to add this in the request for future update. Thank you!

댓글을 달려면 로그인하십시오.

카테고리

태그

질문:

2017년 3월 28일

편집:

2022년 7월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by