Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

null converted to [] #91

Closed
nickanthony-dgl opened this issue Jun 6, 2023 · 3 comments
Closed

null converted to [] #91

nickanthony-dgl opened this issue Jun 6, 2023 · 3 comments

Comments

@nickanthony-dgl
Copy link

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

ans =

    '{
     	"myNullValue":[]
     }
     '

The problem appears to be here: https://github.com/fangq/jsonlab/blob/cf573262eb12c1d1dc3668913c1f902e3452f566/loadjson.m#L560

@fangq
Copy link
Member

fangq commented Jun 7, 2023

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: []

@nickanthony-dgl
Copy link
Author

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
Copy link
Member

fangq commented Jun 7, 2023

here is my solution, committed as https://github.com/fangq/jsonlab/commit/747c99b5d434ce9f90097ddc0ad98bf1d5d45964

  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}'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants