JSON nested Parsing Help using $.each - javascript

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"
}
]
}
};

Related

I want some help in populating a tree structure on my webpage from flat structure without Parent/child values

I am trying to build a dynamic tree structure from the JSON response i receive. The JSON is as follows:
var projectViewData = [{
"projectTYpe": "Report",
"Doctor": "Abc",
"Patient": null,
"type": "xyz",
"document":"a.xls"
},{
"projectTYpe": "Report",
"Doctor": "Abc",
"Patient": "Smith",
"type": "xyz",
"document":"a.xls"
},
{
"projectTYpe": "Analysis",
"Doctor": "Abc",
"Patient": null,
"type": "xyz",
"document":"a.xls"
},
{
"projectTYpe": "Report",
"Doctor": "Abc",
"Patient": "Smith",
"type": "xyz",
"document":"a.xls"
}
];
The JSON can have null values which need to be ignored and next value from the object needs to be picked to plot next in the tree. The Object also don't have parent_id/child_id. My approach is to iterate through every object in json and adding it to an array.
This is the final structure I want to be dynamically generated on my page using javascript.
Below is the work i have done till now.
var array = ["<ul class=\"tree\">"];
for (projectdataElem in projectViewData)
{
array.push("<ul>");
var count = 0;
for (x in projectViewData[projectdataElem])
{
if(projectViewData[projectdataElem][x]==null )
{
}
else
{ if(x=='document'){
array.push("<li>" + projectViewData[projectdataElem][x] + "</li>");
for(var i = 0; i< count; i++)
{
array.push("</ul>"); }
}
else{
if((array.indexOf(projectViewData[projectdataElem][x]))== -1){
console.log(array.indexOf(projectViewData[projectdataElem][x]));
console.log(projectViewData[projectdataElem][x]);
//array.push("<li>" + projectViewData[projectdataElem][x] + "</li>");
array.push("<li>");
array.push(projectViewData[projectdataElem][x]);
array.push("</li>");
array.push("<ul>");
count += 1;
}
}
}
}
array.push("</ul>");
}
array.push("</ul>");
$("#list1").html(array.join(""));
//printList("string");
console.log(array);
Any leads would be highly appreciated.

Evaluating key values in multi-dimensional object

I have a multi-dimensional object that looks like this:
{
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}
I am trying to evaluate the value of "total" in "links." I can do this in a one-dimensional array, like this:
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (!isNaN(data[i][key])) {
data[i][key] = +data[i][key];
}
}
};
But I have not been able to figure out how to do this in two-dimensions (especially calling the value of key "total" by name).
Can anybody set me on the right track? Thank you!
Starting from the principle that the structure of your array is this, you can to iterate the keys and the values:
var obj = {
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
};
for (var key in obj){
obj[key].forEach(function(item){
for(var subkey in item){
if (subkey == 'total')
console.log(item[subkey]);
};
});
};
You can get total using reduce
check this snippet
var obj = {
"links": [{
"source": "58",
"target": "john",
"total": "95"
}, {
"source": "60",
"target": "mark",
"total": "80"
}, {
"source": "60",
"target": "mark",
"total": "80"
}],
"nodes": [{
"name": "john"
}, {
"name": "mark"
}, {
"name": "rose"
}]
}
var links = obj.links;
var sum = links.map(el => el.total).reduce(function(prev, curr) {
return parseInt(prev, 10) + parseInt(curr, 10);
});
console.log(sum);
Hope it helps
Extract the values from the array, convert them to numbers and add them up.
Array.prototype.map() and Array.prototype.reduce() are pretty helpful here:
var data = {"links":[{"source":"58","target":"john","total":"95"},{"source":"60","target":"mark","total":"80"}], "nodes":[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]};
var sum = data.links.map(function(link) {
return +link.total;
}).reduce(function(a, b) {
return a + b;
});
console.log(sum);

How to loop json array to get key and value in javascript?

I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};

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>

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