JSON decode / encode eats arrays

조회 수: 11 (최근 30일)
D R
D R 2018년 10월 12일
댓글: Guillaume 2019년 7월 19일
Hello, can anyone having a Matlab license report this bug to Mathworks?
On certain strings jsondecode / jsonencode in Matlab eat arrays.
First example reproduces the original JSON string correctly:
json_inst = jsondecode ('{"array":[{"a":"b"},{"c":"d"}]}');
jsonencode (json_inst)
ans =
'{"array":[{"a":"b"},{"c":"d"}]}'
In the following example, codec eats the internal array in JSON string:
json_inst = jsondecode ('{"array":[{"a":"b"}]}');
jsonencode (json_inst)
ans =
'{"array":{"a":"b"}}'
The second case is the bug.

답변 (1개)

Guillaume
Guillaume 2019년 7월 19일
Not sure why Walter revived this old question but now that I've seen it: For the record, while inconvenient in the above scenario, I don't think it is a bug but an inherent limitation of the way matlab decode json data.
Matlab will decode a json array either as a plain array if all the elements are the same type or as a cell array if the array is heterogeneous.
So, [{"a":"b"}, {"c":"d"}] is a json array with two objects with different fields, which get decoded as two different structures in matlab and hence stored in a cell array:
{struct('a', 'b'); struct('c', 'd')} %2x1 cell array of scalar structures
However, [{"a":"b"}, {"a":"c"}] is a json array where all the objects have the same field 'a', so this gets decoded as a structure array:
struct('a', {'b'; 'c'}) %2x1 structure array
Of course, in the degenerate case where the array has only one element, matlab can't know if it's meant to store homogeneous or heteregeneous objects. It defaults to homogeneous hence the result is a 1x1 structure array.
Note that even ignoring this issue, there are plenty of other scenarios where the json matlab writes won't be the same as what it read.
  댓글 수: 2
Walter Roberson
Walter Roberson 2019년 7월 19일
(Someone asked a jsondecode question, and while I was researching it, I noticed that this question would benefit from reformatting the code.)
Guillaume
Guillaume 2019년 7월 19일
AH, well at least now it's answered even if the OP may not be around to read the reply.

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

카테고리

Help CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by