Chris Dixon
Chris Dixon

Reputation: 9167

JSON.stringify an object with Knockout JS variables

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?

Upvotes: 20

Views: 27494

Answers (3)

Richard Dalton
Richard Dalton

Reputation: 35793

Knockout has a built in toJSON function to do exactly this:

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.

Upvotes: 47

ebram khalil
ebram khalil

Reputation: 8321

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))

Upvotes: 5

Paul Manzotti
Paul Manzotti

Reputation: 5147

Have you looked at the knockout mapping plugin?

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

Upvotes: 3

Related Questions