I want to convert indexed Object response to proper JSON. I’ve already tried using JSON.stringify but no success. Here is the response:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var catsorted;
$(document).ready(function () {
getCategoriesSorted();
var recordset = catsorted;
//console.log(recordset);
var rset = GenerateNestedJSON(recordset);
var arr = rset;
console.log(arr);
});
function GenerateNestedJSON(recordset) {
var array = recordset;
async function getNestedChildren(arr, parent) {
var children = [];
for (var i = 0; i < arr.length; ++i) {
if (arr[i].parentid == parent) {
var grandChildren = await getNestedChildren(arr, arr[i].id);
if (grandChildren.length) {
arr[i].children = grandChildren;
}
children.push(arr[i]);
}
}
return children;
}
nest = getNestedChildren(array, 0);
return nest;
}
function getCategoriesSorted() {
$.ajax({
type: 'POST',
url: '/CategorieService.asmx/GetCategoriesSorted',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (response) {
catsorted = response.d;
},
error: function (xhr) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
</script>
</head>
<body>
</body>
</html>
getCategoriesSorted() calls a C# webservice. This webservice returns id, parentid and catname from a table. GenerateNestedJSON(recordset) nests children for each category.