JSON.stringify an object with Knockout JS variables

24,824

Solution 1

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.

Solution 2

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

Solution 3

Have you looked at the knockout mapping plugin?

var unmapped = ko.mapping.toJS(viewModel);
Share:
24,824
Chris Dixon
Author by

Chris Dixon

I'm a Senior Programmer specialising in .NET Core (C#), JavaScript (Vanilla/MVVM) and surrounding technologies. LinkedIn: https://www.linkedin.com/in/chris-dixon-69938829

Updated on July 09, 2022

Comments

  • Chris Dixon
    Chris Dixon almost 2 years

    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?