65.9K
CodeProject is changing. Read more.
Home

Serialize Kendo Treeview Data in JSON

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Aug 26, 2013

CPOL
viewsIcon

31441

How to serialize a kendo treeview current view into JSON data

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:

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

The jQuery code is pretty simple too:

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.