JSON decode / encode eats arrays
16 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
Guillaume
am 19 Jul. 2019
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 Kommentare
Walter Roberson
am 19 Jul. 2019
(Someone asked a jsondecode question, and while I was researching it, I noticed that this question would benefit from reformatting the code.)
Guillaume
am 19 Jul. 2019
AH, well at least now it's answered even if the OP may not be around to read the reply.
Siehe auch
Kategorien
Mehr zu JSON Format finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!