Serializing Knockout ViewModels to JSON: Quotes matter

The Knockout MVVM framework makes it dirt simple to serialize your ViewModels to JSON:

ko.toJSON(viewModel);

However, if you’re wondering why some observables aren’t being serialized, note that observables that are initialized empty aren’t serialized to JSON. So if your viewmodel isn’t serializing fully, make sure you’re setting a value for each observable.

So, for example, this won’t be serialized:
firstName: ko.observable()

But, slap in some empty quotes, and it will be serialized:
firstName: ko.observable('')

Here’s a jsfiddle that displays the behavior. As you can see, this behavior applies regardless of whether you use the revealing module pattern.

Subscribe to Email Updates (No spam. Just new posts.)

Comments are closed.