JSON.stringify 一个带有 Knockout JS 变量的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15087710/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:45:48  来源:igfitidea点击:

JSON.stringify an object with Knockout JS variables

javascriptjsonknockout.js

提问by Chris Dixon

Current scenario:

当前场景:

function Employee(data) {
var self = this;

// variables
this.Forename = ko.observable(data.Forename);
this.Surname = ko.observable(data.Surname);

this.Save = function () {
    var obj = JSON.stringify(self); // Without ko.observables, this works fine. self() doesn't work obviously.
    console.log(obj);
};
}

I think what I'm trying to do is pretty straight forward, get all the observable values without going through every single one of them, and creating a JSON string using the stringify function. This is easy to do without observables, is there a simple way to do it with them?

我认为我想要做的很简单,获取所有可观察值,而无需遍历其中的每一个,并使用 stringify 函数创建一个 JSON 字符串。没有 observables 这很容易做到,有没有一种简单的方法可以用它们来做?

回答by Richard Dalton

Knockout has a built in toJSONfunction to do exactly this:

Knockout 有一个内置的toJSON函数来做到这一点:

var json = ko.toJSON(viewModel);

ko.toJSON— this produces a JSON string representing your view model's data. Internally, it simply calls ko.toJS on your view model, and then uses the browser's native JSON serializer on the result. Note: for this to work on older browsers that have no native JSON serializer (e.g., IE 7 or earlier), you must also reference the json2.js library.

ko.toJSON— 这会生成一个 JSON 字符串,表示您的视图模型的数据。在内部,它只是在您的视图模型上调用 ko.toJS,然后在结果上使用浏览器的本机 JSON 序列化程序。注意:为了在没有原生 JSON 序列化程序的旧浏览器(例如,IE 7 或更早版本)上工作,您还必须引用 json2.js 库。

回答by ebram khalil

You can do this by 2 ways :

你可以通过两种方式做到这一点:

first:

第一的:

      var json = ko.toJSON(ko.mapping.toJS(viewModel))

Second

第二

      var json = JSON.stringify(ko.mapping.toJS(viewModel))

回答by Paul Manzotti

Have you looked at the knockout mapping plugin?

你看过淘汰赛地图插件吗?

var unmapped = ko.mapping.toJS(viewModel);