JSON decode / encode eats arrays

16 次查看(过去 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.

请先登录,再进行评论。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by