Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout serialization with ko.toJSON - how to ignore properties that are null

When using:

var dataToSave = ko.toJSON(myViewModel);

.. is it possible to not serialize values that are null?

Serializing my current viewModel creates around 500Kb of JSON most of which is ends up like:

"SomeObject": {
    "Property1": 12345,
    "Property2": "Sometext",
    "Property3": null,
    "Property4": null,
    "Property5": null,
    "Property6": null,
    "Property7": null,
    "Property8": null,
    "Property9": false
}

If I could get the serializer to ignore null values then this could be reduced down to:

"SomeObject": {
    "Property1": 12345,
    "Property2": "Sometext",
    "Property9": false
}

Any ideas how I can instruct the serializer to ignore the null values??

like image 872
Mark Robinson Avatar asked Sep 17 '12 14:09

Mark Robinson


2 Answers

Remember that ko.toJSON is just a modification of JSON stringify. You can pass in a replacer function.

As an example of using a replacer function in Knockout, I put together a JSFiddle based on one of the knockout tutorials. Notice the difference between the makeJson and makeCleanJson functions. We can choose not to return any values in our replacer function and the item will be skipped in the JSON string.

self.makeJson = function() {
    self.JsonInfo(ko.toJSON(self.availableMeals));
};

self.makeCleanJson = function() {
    self.JsonInfo(ko.toJSON(self.availableMeals, function(key, value) {
        if (value == null)
        {
            return;
        }
        else
        {
            return value;
        }
    }));
};
like image 186
deltree Avatar answered Oct 27 '22 18:10

deltree


You can add a toJSON method to your view model and use that to remove all the unneeded properties:

 ViewModel.prototype.toJSON = function() {
     var copy = ko.toJS(this);
     // remove any unneeded properties
     if (copy.unneedProperty == null) {
         delete copy.unneedProperty;
     }
     return copy;
 }

You could probably automate it to run through all your properties and delete the null ones.

like image 33
Matt Burland Avatar answered Oct 27 '22 16:10

Matt Burland