joelvh / json2json

Transform (reformat) JSON structures from one to another using JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Handling null properties

mikejpeters opened this issue · comments

As far as I understand, json2json ignores any null or undefined properties when transforming:

new json2json.ObjectTemplate({all: true}).transform({
  a: null,
  b: 1
});
{b: 1}

I think this is due to logic in ObjectTemplate#aggregateValue().

For my purposes I need to include these properties in the transformed result. Removing the line works for me, but obviously may not be desired for everyone.

Can I create a PR with a new config option (e.g. includeNull with default false or ignoreNull with default true) so that the default behavior doesn't change but it is configurable? On a related note I think it would be very useful to be able to set global options / defaults so that I wouldn't need to use this option everywhere, but I'm not sure how hard that would be to add to this project.

@mikejpeters I think it makes sense that you'd want to keep attributes with empty values. Is it only for null or undefined, or is it also ignoring anything "falsey"? That would dictate if the option is #ignoreNull or #ignoreEmpty.

Also, make sure to look at any other places in the code where these values may be ignored, to add that option check.

Lastly, does TemplateConfig handle the global options for you?

I'm not sure how to use TemplateConfig for setting global options. Are you suggesting that it is already possible using that class, or that it would be the appropriate place to add that functionality? (I think for my own specific scenario I have found another way to deal with this, but I'm curious in case it could be useful later.)

@mikejpeters I believe that is the global config that gets passed into the ObjectTemplate and is referenced throughout. Look at the constructor and you will see.

@mikejpeters by the way, the {all: true} hash you use in your example in this issue gets passed to the TemplateConfig constructor.