fangq/jsonlab

`null` converted to `[]`

Closed this issue · 3 comments

JSON null values are not round-tripped. For example, this savejson(loadjson('{"myNullValue": null}')) results in:

ans =

    '{
     	"myNullValue":[]
     }
     '

The problem appears to be here:

if pos+3 <= len && strcmpi(inputstr(pos:pos+3), 'null')

fangq commented

matlab does not have a built-in data structure that is equivalent to null - the closest is [].

if you run matlab's built-in jsondecode function, it also maps null to '[]'

>> jsondecode('{"a":null}')

ans = 

  struct with fields:

    a: []

Yes, the problems I was running into with the built-in JSON functions are actually the reason I've started using JSONLab. Wouldn't it be possible to create a custom class to act as json null type?

fangq commented

here is my solution, committed as 747c99b

  1. define an optional flag, for example, EmptyArrayAsNull, set to 0 by default, but can be enabled in your case
  2. test that flag in this block inside matdata2json(), and return null if enabled.

this should give you what you want, i.e.

>> savejson('', loadjson('{"a":{},"b":[],"c":null}'), 'EmptyArrayAsNull',0, 'Compact', 1)

ans =

    '{"a":[],"b":[],"c":[]}'

>> savejson('', loadjson('{"a":{},"b":[],"c":null}'), 'EmptyArrayAsNull',1, 'Compact', 1)

ans =

    '{"a":null,"b":[],"c":null}'