Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Serialize Kendo Treeview Data in JSON

5.00/5 (3 votes)
26 Aug 2013CPOL 31.4K  
How to serialize a kendo treeview current view into JSON data

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

There are times that you may want to serialize your kendo treevew's view and store it somewhere so you can load it back later. This article provides a quick and simple way to serialize the treeview data by using a few lines of jQuery code.

Use Case

In our use case, we have a treeview with checkboxes to display heirarchical data. Users may select items they want in the treeview by checking the checkboxes and save them as part of their preference settings. Once it's saved, we also need to be able to load it back from the data.

Using the code

The test HTML code has just the treeview div section:

JavaScript
<body>
  <div id="treeview"></div>
</body>

The jQuery code is pretty simple too:

JavaScript
var ds = new kendo.data.HierarchicalDataSource({
    data: [{"text":"Item 1","id":"1","expanded":true,
      "checked":true,"items":[{"text":"Item 1.1",
      "id":"2","checked":true},{"text":"Item 1.2",
      "id":"3","checked":true},{"text":"Item 1.3",
      "id":"4","checked":true}]},{"text":"Item 2",
      "id":"5","expanded":true,"items":[{"text":"Item 2.1",
      "id":"6","checked":true},{"text":"Item 2.2",
      "id":"7"},{"text":"Item 2.3","id":"8",}]},
      {"text":"Item 3","id":"9"}]
});

var tv = $("#treeview").kendoTreeView({
    checkboxes: {
        checkChildren: true
    },
    dataSource: ds
}).data("kendoTreeView");


function treeToJson(nodes) {

    return $.map(nodes, function(n, i) {
    
        var result = { text: n.text, id: n.id, expanded: n.expanded, checked: n.checked };
    
        

        if (n.hasChildren)
            result.items = treeToJson(n.children.view());

        return result;
    });
}

var json = treeToJson(tv.dataSource.view()); 
console.log(JSON.stringify(json));

The function treetoJson() will loop through all the tree nodes and return the array of data in JSON.

You can test it on JS Bin. Make sure you include "Kendo UI" by clicking on the "Add Library" link.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)