Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 276
Chris Dixon Avatar asked Feb 26 '13 11:02

Chris Dixon


People also ask

Can you JSON Stringify an object?

stringify() JSON stringification is the process of converting a Javascript object to a flat JSON string that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. stringify() , as the Javascript standard specifies.

How do I get Knockout JS data?

prototype. loadNote = function (id) { var self = this; $. getJSON(uri + '/' + id, function (data) { self. note(data); }); }; // Apply bindings ko.

What does Ko unwrap do?

unwrap method is used to read it), the current viewModel and bindingContext. Whenever the passed value changes the binding will print updated information to console. This binding cannot be used with virtual elements (in html comments), only on real elements, since ko.

What does JSON Stringify () method do?

JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

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.

like image 185
Richard Dalton Avatar answered Sep 28 '22 01:09

Richard Dalton


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))
like image 32
ebram khalil Avatar answered Sep 28 '22 02:09

ebram khalil