After making a POST request using AJAX I get the following JSON response:
{
"ServiceName": "ABC",
"Response": {
"Object": [
{
"Attributes": {
"Attribute": [
{
"AttributeName": "Name",
"AttributeValue": "XYZ"
},
{
"AttributeName": "Place",
"AttributeValue": "Abc"
},
{
"AttributeName": "Country",
"AttributeValue": "Americas"
},
{
"AttributeName": "Code",
"AttributeValue": "576"
}
]
}
},
{
"Attributes": {
"Attribute": [
{
"AttributeName": "Name",
"AttributeValue": "XYZHJ"
},
{
"AttributeName": "Place",
"AttributeValue": "Abchgh"
},
{
"AttributeName": "Country",
"AttributeValue": "India"
},
{
"AttributeName": "Code",
"AttributeValue": "536"
}
]
}
}
]
}}
I am using datatable to display the data.. but with this nested JSON I am not able to go straight for the data. I am using this https://datatables.net/examples/server_side/post.html https://datatables.net/reference/option/ajax.dataSrc for reference.
You must iterate over the response and convert it into a format dataTables can comprehend. As I read the sample data you have an Object holding blocks of Attributes holding an Attribute with key => value pairs as AttributeName => AttributeValue. So parse the response in a dataSrc callback :
var table = $("#example").DataTable({
ajax : {
url : 'nestedData.json',
dataSrc : function(json) {
var temp, item, data = [];
for (var i=0;i<json.Response.Object.length;i++) {
temp = json.Response.Object[i].Attributes.Attribute;
item = {};
for (var elem in temp) {
item[temp[elem].AttributeName] = temp[elem].AttributeValue
}
data.push(item);
}
return data
}
},
columns : [
{ data : 'Name', title : 'Name' },
{ data : 'Place', title : 'Place' },
{ data : 'Country', title : 'Country' },
{ data : 'Code', title : 'Code' }
]
})
the dataSrc callback return an array of objects on the form :
data = [
{ Code: "576", Country: "Americas", Name: "XYZ", Place: "Abc" },
{ Code: "536", Country: "India", Name: "XYZHJ", Place: "Abchgh" }
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With