fangq/jsonlab

Can't encode an empty struct array

goretkin opened this issue · 1 comments

>> savejson('', repmat(struct('a', 1, 'b', 2), 0, 2), 'test.json')
Index exceeds the number of array elements. Index must not exceed 0.

Error in jdataencode>N_ (line 398)
newname=[varargin{1}.prefix name];

Error in jdataencode>@(x)N_(x,varargin{:}) (line 180)
N=@(x) N_(x,varargin{:});

Error in jdataencode>mat2jd (line 181)
newitem=struct(N('_ArrayType_'),class(item),N('_ArraySize_'),size(item));

Error in jdataencode>obj2jd (line 108)
    newitem=mat2jd(item,varargin{:});

Error in jdataencode>struct2jd (line 146)
        newitem.(names{i})=obj2jd(item.(names{i}),varargin{:});

Error in jdataencode>obj2jd (line 106)
    newitem=struct2jd(item,varargin{:});

Error in jdataencode>struct2jd (line 146)
        newitem.(names{i})=obj2jd(item.(names{i}),varargin{:});

Error in jdataencode>obj2jd (line 106)
    newitem=struct2jd(item,varargin{:});

Error in jdataencode (line 98)
jdata=obj2jd(data,opt);

Error in savejson (line 183)
    obj=jdataencode(obj,'Base64',1,'UseArrayZipSize',0,opt);
 
398 newname=[varargin{1}.prefix name];
K>> 

It seems like this could just be handled by widening the condition on

if(num>1) % struct array

to apply for n != 1, but this will cause the JSON to lose the information about the field names of the empty struct array.

>> bs   = repmat(struct('a', 1, 'b', 2), 0, 2)

bs = 

  0×2 empty struct array with fields:

    a
    b

>> fieldnames(bs)

ans =

  2×1 cell array

    {'a'}
    {'b'}

is there a special value to use in the JSON to represent the empty array?