1

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

1

1 Answer 1

4

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.

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

Comments

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.