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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeJSON Format についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by