使用ko.toJSON进行淘汰序列化-如何忽略为空的属性 [英] Knockout serialization with ko.toJSON - how to ignore properties that are null
问题描述
使用时:
var dataToSave = ko.toJSON(myViewModel);
..是否可以不序列化为空的值?
.. is it possible to not serialize values that are null?
序列化我当前的viewModel会创建大约500Kb的JSON,其中大部分最终显示为:
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
}
有什么想法可以指示序列化程序忽略空值?
推荐答案
请记住 ko.toJSON 只是对 JSON字符串化.您可以传入替换函数
Remember that ko.toJSON is just a modification of JSON stringify. You can pass in a replacer function.
作为在Knockout中使用替换功能的示例,我基于以下内容整理了 JSFiddle 淘汰教程中.注意makeJson
和makeCleanJson
函数之间的区别.我们可以选择在我们的replacer函数中不返回任何值,并且该项目将在JSON字符串中被跳过.
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;
}
}));
};
这篇关于使用ko.toJSON进行淘汰序列化-如何忽略为空的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!