Fetching a json from jsp and displaing on javascript - javascript

I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.

Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);

Related

How to loop through jason data and display it in data list tag (dl)

I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

JSON dependent dynamic dropdown third level array error

I have three dropdowns which are depend on each other. Based on the selection of Dropdown A will have a list of results in Dropdown B, and based on the selection of Dropdown B will have a list of results in Dropdown C.
I can populate the first two dropdowns without a problem. However the last dropdown does shows me incorrect options.
$(function() {
var platforms;
var tasktypes;
var compos;
var jsonData;
$('#addnew').click(function(){
$('#dataset').clone().appendTo($('#newfield'));
});
$.getJSON('tasks.json', function(result) {
jsonData = result;
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
$("#platform").change(function (){
var idx = $("#platform").prop('selectedIndex');
var platforms = jsonData[idx].task;
tasktypes = "";
for (i = 0; i < platforms.length; i++) {
tasktypes += "<option value='" +
platforms[i].taskname +
"'>" +
platforms[i].taskname +
"</option>";
};
$('#taskname').html(tasktypes);
});
$("#taskname").change(function (){
var idc = $("#taskname").prop('selectedIndex');
var tasktypes = jsonData[idc].task[0].component;
compos = "";
for (i = 0; i < tasktypes.length; i++) {
compos += "<option value='" +
tasktypes[i].componentname +
"'>" +
tasktypes[i].componentname +
"</option>";
};
$('#components').html(compos);
});
});
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<button id="addnew">Add new</button>
<div id="dataset">
Platform:
<select id="platform">
</select>
Task Type:
<select id="taskname">
</select>
Component:
<select id="components">
</select>
Units:
<input type="number" min="0" />
</div>
<div id="newfield"></div>
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Json
[
{
"name": "Sitecore",
"value": "sitecore",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "A",
"time": "20"
},
{
"componentname": "B",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "C",
"time": "20"
},
{
"componentname": "D",
"time": "10"
}
]
}
]
},
{
"name": "Siab",
"value": "siab",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "E",
"time": "20"
},
{
"componentname": "F",
"time": "10"
}
]
},
{
"taskname": "newswire",
"component": [
{
"componentname": "G",
"time": "20"
},
{
"componentname": "H",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "I",
"time": "20"
},
{
"componentname": "J",
"time": "10"
}
]
}
]
}
]
First two dropdowns works fine. Once I select a platform from the first dropdown, second dropdown populates with the relevant tasknames. But once I select a taskname from the second dropdown, third dropdown does show irrelevant data. I can't figure out what's wrong I'm doing here.
I believe the major problem you have is jsonData = result during the ajax request. All ajax requests are asynchronous by default, hence, every data produced from it is mostly non-existent after the request completion. So your best bet will be to pass result to the HTML DOM object during the request.
$.getJSON('tasks.json', function(result) {
$('#platform').data('jsonData',result);//Assign Json data to data object of platform id
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});

Dynamic table from JSON using javascript

I use the following json to develop a table structure. But I'm unable to go ahead on adding rows according to columns.
[
{
"authType": "BasicAuth",
"phases": [
{
"type": "Development",
"keys":[{
"username": "developer"
},{
"password": "password123"
}]
},
{
"type": "Testing",
"keys":[{
"username": "tester"
},{
"password": "password123"
}]
}
]
},
{
"authType": "AccessToken",
"phases": [
{
"type": "Development",
"keys":[{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/developer"
}]
},
{
"type": "Testing",
"keys":[{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/testing"
}]
}
]
},
{
"authType": "OAuth",
"phases": [
{
"type": "Development",
"keys":[{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/development"
}]
},
{
"type": "Testing",
"keys":[{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/testing"
}]
}
]
}
]
I use the following script to iterate over the json.
var subTable = '<div class="subtable"><table data-clicked-parent-row="'+ clickedCell.row
+'" data-clicked-column="'+ clickedCell.column +'"><tr><th>Keys</th>';
tableData.forEach(function(e){
if(rowType == e.authType){
var phases;
e.phases.forEach(function(t){
subTable += '<th>'+ t.type +'</th>'
})
return subTable + '</tr></table></div>';
}
})
The thing is, I'm unable to add rows to the table while iterating on the objects. The following is a static version of the table. how can i write a generic function to achive the following table structure. Please let me know any better way to write the iteration.
var data = {
"Items": [
{
"id": "A004"
, "name": "ACC LR2"
, "userId": ["1","2","3","4"]
}, {
"id": "0001"
, "name": "ABG IT"
, "userId": ["8","9","10","11"]
}
]
}
function getUserId(obj){
result = []
obj.Items.forEach( function(item, i){
result.push(item.userId);
});
return result;
}
function getUserIdAll(obj){
result = []
obj.Items.forEach( function(item, i){
result = result.concat(item.userId);
});
return result;
}
console.log( getUserId(data) );
console.log( getUserIdAll(data) );
var data = [
{
"authType": "BasicAuth",
"phases": [
{
"type": "Development",
"keys": [
{
"username": "developer"
},
{
"password": "password123"
}
]
},
{
"type": "Testing",
"keys": [
{
"username": "tester"
},
{
"password": "password123"
}
]
}
]
},
{
"authType": "AccessToken",
"phases": [
{
"type": "Development",
"keys": [
{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/developer"
}
]
},
{
"type": "Testing",
"keys": [
{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/testing"
}
]
}
]
},
{
"authType": "OAuth",
"phases": [
{
"type": "Development",
"keys": [
{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/development"
}
]
},
{
"type": "Testing",
"keys": [
{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/testing"
}
]
}
]
}
];
function objGetKeyVal(obj){
for (var key in obj) {
return [ key, obj[key] ];
}
}
(function createTable(tableData){
var table = '<table>';
// tableHeader += '<caption>Caption</caption>';
// Creating table header
// table += '<tr>';
// table += '<th>Keys</th>';
// table += '<th>Development</th>';
// table += '<th>Testing</th>';
// table += '</tr>';
// Sub tables iterator
tableData.forEach(function(subTable, i){
tableRows = []; // Rows array for sub table
table += '<tr><th>Keys</th>'; // Table headers creating
subTable.phases.forEach(function(colData, icol){
table += '<th>'+colData.type+'</th>'; // Creating table headers for each phases
colData.keys.forEach(function(key, irow){ // Converts structured data to array of rows arrays of columns
if( tableRows[irow] === undefined) { tableRows[irow] = []; }
rowData = objGetKeyVal(key);
tableRows[irow][0] = rowData[0];
tableRows[irow][icol+1] = rowData[1];
});
});
table += '</tr>'; // End table header cration
// Now we have usual table array - need only convert it to HTML
// table looks like: [ ['col1', 'col2', 'col3'], ['col1', 'col2', 'col3'] ]
table += '<tr><th colspan="3">'+subTable.authType+'</th></tr>';
tableRows.forEach(function(row){
table += '<tr>';
row.forEach(function(str){
table += '<td>'+str+'</td>';
});
table += '</tr>';
});
});
table += '</table>';
$('body').append(table);
})(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use this function for render table with json. Observe this function works with simple json. For complex json necessary adapter this function
var tableData = [
{
"Name": "Kevin",
"Adress": "Adress UHE, SC",
},
{
"Name": "Jose",
"Adress": "Adress KUK, CC",
},
{
"Name": "Kevin",
"Adress": "Adress CGH, JK",
}
];
function compile(){
var subTable = '', column = '', row = '';
for(c in tableData[0])
column += '<th>' + c + '</th>';
for(item in tableData){
row += '<tr>';
for(c in tableData[0]) row += '<td>' + tableData[item][c] + '</td>';
row += '</tr>';
}
console.log(row)
return '<table border="solid 1px"><tr>' + column + '</tr>' + row + '</table>';
};
document.write(compile());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JSON nested Parsing Help using $.each

Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

Categories

Resources