使用 ko.toJSON 进行淘汰赛序列化 - 如何忽略为 null 的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12461037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout serialization with ko.toJSON - how to ignore properties that are null
提问by Mark Robinson
When using:
使用时:
var dataToSave = ko.toJSON(myViewModel);
.. is it possible to notserialize values that are null?
.. 是否可以不序列化空值?
Serializing my current viewModel creates around 500Kb of JSON most of which is ends up like:
序列化我当前的 viewModel 会创建大约 500Kb 的 JSON,其中大部分是这样的:
"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??
任何想法如何指示序列化程序忽略空值?
回答by deltree
Remember that ko.toJSONis just a modification of JSON stringify. You can pass in a replacer function.
请记住,ko.toJSON只是JSON stringify的修改。你可以传入一个替换函数。
As an example of using a replacer function in Knockout, I put together a JSFiddlebased on one of the knockout tutorials. Notice the difference between the makeJsonand makeCleanJsonfunctions. We can choose not to return any values in our replacer function and the item will be skipped in the JSON string.
作为在 Knockout 中使用替换函数的示例,我根据其中一个淘汰赛教程组合了一个JSFiddle。注意makeJson和makeCleanJson函数之间的区别。我们可以选择在替换器函数中不返回任何值,该项目将在 JSON 字符串中被跳过。
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;
}
}));
};
回答by Matt Burland
You can add a toJSON method to your view model and use that to remove all the unneeded properties:
您可以向视图模型添加 toJSON 方法并使用它来删除所有不需要的属性:
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.
您可能会自动运行它以遍历所有属性并删除空属性。

