KnockoutJS - ko.toJSON copying unwanted properties

KnockoutJS - ko.toJSON copying unwanted properties

Javascript, JSON, KnockoutJS

When using KnockoutJS and the Knockout Mapping Plugin, you may notice extra properties are being serialized with your viewmodels, ex. "__ko_mapping__" or "copiedProperties" objects.

JSON Example:

{
	"MyObject": {
		"Id": "00000000-0000-0000-0000-000000000000",
		"Type": 1,
		"Name": "Default MyObject"
	},
	"__ko_mapping__": {
		"ignore": [],
		"include": ["_destroy"],
		"copy": [],
		"observe": [],
		"mappedProperties": {
			"MyObject.Id": true,
			"MyObject.Type": true,
			"MyObject.Name": true
		},
		"copiedProperties": {},
		"": {}
	},
	"someOtherSettings": ["Yes", "No"]
}

These are just extra objects included with the KO mapping plugin. To remove these properties from your JSON, Use the KnockoutMapping serializer instead of using the vanilla KnockoutJS serializer.

Remove:

var vm = ko.toJS(MyViewModel);
var vm = ko.toJSON(MyViewModel);

Replace with:

var vm = ko.mapping.toJS(MyViewModel);
var vm = ko.mapping.toJSON(MyViewModel);

 

Happy coding!



Back to The Programmer Blog