Reputation: 39248
In KnockoutJS is there a way to serialize nested structures of observable arrays to JSON? I am using JSON.stringify, but since it doesn't access the arrays as someObservableArray(), it will not be able to serialize the nested arrays:
Ex: I have an observable array where each item contains an observable array as a property .
Currently I am manually converting it to a standard JS object before calling JSON.stringify, but is there another knockout function that will enable me to convert it to JSON directly
Upvotes: 1
Views: 2672
Reputation: 139758
You can use the ko.toJSON
function which can serialize nested observable structures to JSON:
var vm = {
someObservableArray: ko.observableArray(
[{
prop: ko.observable('val1'),
childArray: ko.observableArray([{
prop2: ko.observable('vla2')
}, {
prop2: ko.observable('val3')
}])
}, {
prop: ko.observable('val4'),
childArray: ko.observableArray([{
prop2: ko.observable('val5')
}, {
prop2: ko.observable('val6')
}])
}])
}
console.log(ko.toJSON(vm));
// output: {"someObservableArray":[{"prop":"val1","childArray":[{"prop2":"vla2"},
// {"prop2":"val3"}]},{"prop":"val4","childArray":[{"prop2":"val5"},
// {"prop2":"val6"}]}]}
Demo JSFiddle.
Upvotes: 4