20

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?

3 Answers 3

47

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually, this is even better as it doesn't require another library. Awesome.
i think you have first to convert the observable into normal JS object then call ko.toJSON on it.
True, I tend to use the mapping one in case I need the greater flexibility of ignoring certain properties. Also, I can't see any reference in the mapping documentation about whether it needs json2.js to work in older browsers. If it doesn't, then that's obviously an advantage.
@PaulManzotti Just checked the source code and the mapping plugin uses ko.utils.stringifyJson which has the same requirements of a built in serializer.
@RichardDalton Ah, cheers for looking into that, good to know.
5

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

1 Comment

And then ko.toJSON(ko.mapping.toJS($root), null, 2) :)
3

Have you looked at the knockout mapping plugin?

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

1 Comment

One of those "d'oh, why didn't I think of that?" moments! Cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.