使用 ko.toJSON 进行淘汰赛序列化 - 如何忽略为 null 的属性 [英] Knockout serialization with ko.toJSON - how to ignore properties that are null

查看:17
本文介绍了使用 ko.toJSON 进行淘汰赛序列化 - 如何忽略为 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 stringify 的修改.您可以传入替换函数.

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

作为在 Knockout 中使用替换函数的一个例子,我整理了一个 JSFiddle 基于一个淘汰赛教程.请注意 makeJsonmakeCleanJson 函数之间的区别.我们可以选择在替换器函数中不返回任何值,该项目将在 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 进行淘汰赛序列化 - 如何忽略为 null 的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆