Looping through JSON in Javascript and listing as a UL - javascript

Here is a snippet of the JSON my PHP script is echoing out:
[
{
"title": "4th of July",
"start": "2014-07-04"
},
{
"title": "5th of May",
"start": "2014-05-05"
},
{
"title": "My Birthday",
"start": "2014-02-03"
}
]
Im trying to loop through all the events and list them out.
The problem Im having is getting into the deeper section of the data. Can someone help me?
Also what if I was to add an array deeper down? Like this:
[
{
"title": "4th of July",
"start": "2014-07-04",
"activities": [
"badmitten",
"tennis"
]
}
]
Here is what I've tried:
$.getJSON("json.json", function(data) {
var items = [];
$.each(data, function(key, val) {
//items.push("<li id='" + key + "'>" + val + "</li>");
});
$.each(data, function(obj) {
$.each(obj, function(key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
});
});

try:
var data = [
{
"title": "4th of July",
"start": "2014-07-04"
},
{
"title": "5th of May",
"start": "2014-05-05"
},
{
"title": "My Birthday",
"start": "2014-02-03"
}
]
data.forEach(function(d){
// do whatever to each of the item in the array
console.log(d.title);
console.log(d.start);
});
for deeper section of the data, just keep drilling down using the same way. Inside the loop above:
if(d.activities && d.activites.length > 0){
d.activities.forEach(function(a){
console.log(a);
})
}
Hope that helps

A little late, since you've already accepted an answer, but if you want it to be dynamic, you could set up a recursive function, like this:
Example
function printSection(obj) {
var items = ['<ul>'];
$.each(obj, function(key, value) {
var item = '<li'+ (isNaN(key) ? ' id="'+ key +'"' : '') +'>';
if (value instanceof Object) {
item += key +':';
item += printSection(value);
} else {
item += value;
}
item += '</li>';
items.push(item);
});
items.push('</ul>');
return items.join('');
}
This way, you can add further levels of nesting without having to change the output loop.
$.getJSON('json.json', function(data) {
var result = [];
$.each(data, function() {
result.push(printSection(this));
});
$('#result').html(result.join(''));
}

Related

Looping through a JavaScript object

I'm trying to loop through this JavaScript object but it's only returning the last key.
Here's my code
var array = [
{
"outfit": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£20"
}
},
{
"outfit": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£720"
}
},
{
"outfit": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£9920"
}
}
];
for(var i=0; i<array.length; i++){
console.log(array[i]);
$('.slide .content').each(function(index){
if(i == index) {
console.log(i + "==" + index);
var contentDiv = $('.slide .content')[index];
contentDiv.innerHTML = "";
contentDiv.innerHTML = ''+ array[i].title + '<span>'+ array[i].price +'</span>'
}
});
}
I'm basically trying to loop through the data, extracting it for a look-book carousel. Then append each piece of data in $('.slide .content') for each slide of the carousel.
Any help would greatly be appreciated. Many thanks
Edited
var array = [
{
"outfit": [
{
"link": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£20"
},
},
{
"link": {
"url": "http://www.bbc.co.uk",
"title":"Trousers",
"price":"£60"
}
}
]
},
{
"outfit": [
{
"link": {
"url": "http://www.nintendo.co.uk",
"title":"Dress",
"price":"£920"
}
}
]
}
];
array.forEach(function(value, index ){
value.outfit.forEach(function( outfitValue, outfitIndex){
console.log(outfitValue.link.title);
});
});
Result
T-shirt
Trousers
Dress
https://jsfiddle.net/jzpL8dnm/13/
I changed the structure of your code. It may help you to solve your problem.
var array = [
{
"outfit": {
"link": {
"url": "http://www.nintendo.co.uk",
"title":"T-shirt",
"price":"£20"
},
"link": {
"url": "http://www.bbc.co.uk",
"title":"Trousers",
"price":"£60"
}
}
},
{
"outfit": {
"link": {
"url": "http://www.nintendo.co.uk",
"title":"Dress",
"price":"£920"
}
}
}
];
for(var key in array){
console.log(array[key]);
}
I found that if we are having same keys in a JavaScript object then on traversing JavaScript object by transpiler/compiler it will get the updated info of keys. So keys should be unique if you really want to achieve it Associative array are the most convenient way because indexing will help you to retrieve data either the data is duplicate or not.
second way: if you want to use only js object then create array in js object where you have same key.
You have the same keys.
Keys in JS objects must be unique.

Parse JSON dynamically and print key values on html with input checkbox and get a new JSON of selected keys

I am trying to parse an unknown JSON whose format could be anything. So, I dont know the keys to access it. I want to access every key in JSON and print out all keys and values on screen using HTML. So I made a recursive function to access every key in JSON and used a variable name html to print the keys.
here`s the code:
JSON String:
{
"FetchDetails": {
"TransactionDetails": {
"ServiceName": "Airtel Mobile Bill Postpaid",
"officeID": "209",
"BillAmount": "931.00",
"ConsumerName": "Chetan Kumar Yadav",
"consumerKeysValues": "9352423664",
"partPaymentAllow": "1",
"partPaymentType": "Both",
"lookUpId": "6163298",
"officeCodeValue": "RATNC011"
},
"BillDetails": [{
"LableName": "Amount Before Due Date",
"LableValue": "931.00"
}, {
"LableName": "Due Date",
"LableValue": "NA"
}, {
"LableName": "Mobile Number",
"LableValue": "9352423664"
}, {
"LableName": "Amount After Due Date",
"LableValue": "931.00"
}, {
"LableName": "Bill Date",
"LableValue": "NA"
}, {
"LableName": "Consumer Name",
"LableValue": "Chetan Kumar Yadav"
}, {
"LableName": "Bill Cycle",
"LableValue": "NA"
}, {
"LableName": "Bill Number",
"LableValue": "NA"
}, {
"LableName": "Account Number",
"LableValue": "1116231291"
}]
}
}
Heres the code to access every key in Parsed JSON
function scan(info) {
var sub_root = [];
if (info instanceof Object) {
for (k in info) {
if (info.hasOwnProperty(k)) {
console.log('scanning property ' + k);
if (info[k] instanceof Object) {
me += "<div class='root'> <div class='sub_root'> <input class='node' name='sub_root[" + k + "]' value='" + k + "' type='checkbox' />" + k;
console.log(k);
counter++;
scan(info[k]);
me += "</div>";
me += "</div>";
} else {
me += "<div class='json_check' ><input class='node' name='sub_root[" + y + "] [" + k + "]' value='" + k + "' type='checkbox' />" + k + ": " + info[k] + " </div>";
scan(info[k]);
counter++;
}
}
}
} else {
console.log('found value : ' + info);
}
}
After this, I am able to access every key in JSON and printed every node in a nested form with checkboxes in front of them to select any node/key.
Here`s the screenshot:
[PROBLEM to be solved]
Now at the bottom, I have a submit button, when I click on it I want to form a JSON of checked values with their parent nodes. So like if I check a key with a value, I should get its parent keys along with it.
For example: I have selected ServiceName and officeID in TransactionDetails, and some array values in BillDetails, so I should get something like this
{
"FetchDetails": {
"TransactionDetails": {
"ServiceName": "Airtel Mobile Bill Postpaid",
"officeID": "209"
},
"BillDetails": [{
"LableName": "Amount Before Due Date",
"LableValue": "931.00"
}, {
"LableName": "Due Date",
"LableValue": "NA"
}, {
"LableName": "Account Number",
"LableValue": "1116231291"
}]
}
}
[EDITED]
To get this JSON format and traverse through HTML objects I am writing this code:
$('#btn_createservice').on('click', function() {
var solid = '{';
var input = $('input').is(':checked');
if(input){
input = $('input');
}
$('.node:checked').each(function(index) {
var parentEls = $(this).closest(input)
.map(function() {
solid += this.value;
return this.value;
})
.get()
.join( ", " );
console.log(parentEls);
});
solid += '}';
$( ".submit_json" ).html(solid);
});
You need to use .parents(), not .closest() so you get all the containing elements.
Then create containing properties with those names when necessary.
$("#btn_createservice").on("click", function() {
var svc_obj = {};
$(".node:checked").each(function() {
var cur_obj = svc_obj;
$(this).parents(".node").map(function () {
return this.value;
}).get().reverse().forEach(function(name) {
if (!cur_obj[name]) { // create property if it doesn't already exist
cur_obj[name] = {};
}
cur_obj = cur_obj[name]; // use this for next iteration;
});
var thisname = this.name.match(/\[([^[])+\]$/)[1]; // Get property name from name="sub_root[...]"
cur_obj[thisname] = this.value;
});
$(".submit_json").html(JSON.stringify(svc_obj));
})
You need to fix the HTML you're creating so that the checkboxes have value='" + info[k] "'.

Showing formatted JavaScript as content in HTML

Hi I am new to JavaScript and I need to show this JavaScript object (pseudo-JSON) into a div on a HTML page, I can't use jQuery can anyone help please.
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
}
If you want your data to be properly formatted, JSON.stringify will natively do this for you. So in the example below, you can see we pass in the data (ignore the second argument, this is a replacer function to parse the string) and the number of formatting spaces required (in this case 2).
var data = {
"music": [{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
}, ]
};
document.getElementById('target').innerHTML = '<pre><code>' + JSON.stringify(data, null, 2) + '</code></pre>';
pre {
background-color: #eee;
}
<div id="target"></div>
document.getElementById('target').innerHTML sets the html content of an element with `id="target";
The <pre> tag preserves whitespace formatting and the <code> tag tells the browser to render as is.
Not sure which data you want to show in the div. data is an object while music is a key to data. data.music will return the music array. Then use forEach array method to loop through the array.
Hope this snippet will be useful
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
}
var _getData = data.music // will return music array;
_getData.forEach(function(item){
document.write('<pre>'+item.id+'</pre>')
})
JSFIDDLE
You need to use dot notation. See code below
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
};
$('p').text(data.music[0].artist);
See jsfiddle attached
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp; }
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
}); }
var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]}; var str = JSON.stringify(obj, undefined, 4);
output(str); output(syntaxHighlight(str));
Your JS be like
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
}
var item = data.music;
for(var i = 0; i<item.length; i++){
document.write(item[i].id + ", " + item[i].artist);
document.write(item[i].album);
}
JSFiddle

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