How to print data from this JSON Javascript? - javascript

I have the code from json, and i would like to print them out to html page.
{"offset":0,
"results":[
{"link_1/_text":"Reflection",
"text_1":"January 30, 2015",
"link_3":"http://pmj.astaga.com/article/?p=414",
"link_1":"http://pmj.astaga.com/article/?cat=67",
"link_3/_text":"Meditasi: Makna Rasa Sakit",
"text_list_1":["kebahagiaan","meditasi","Meditasi: Makna Rasa Sakit |Matchmatter.com","on pain kahlil gibran","puisi kahlil gibran"],
"image_1":"http://pmj.astaga.com/article/wp-content/uploads/2015/01/Inspirational-Quotes-Image-Khalil-Gibran.jpg",
"title_text":"Meditasi: Makna Rasa Sakit",
"text_2":"Semua manusia yang hidup di dunia ini ingin merasakan kebahagiaan, dalam bentuk apapun."
},
{"link_1/_text":"Love and Sex",
"text_1":"January 26, 2015",
"link_3":"http://pmj.astaga.com/article/?p=411",
"link_1":"http://pmj.astaga.com/article/?cat=64",
"link_2":"http://pmj.astaga.com/article/?cat=65",
"link_3/_text":"Take and Give",
"text_list_1":["memberi dan menerima","men","Take and Give","Women"],
"image_1":"http://pmj.astaga.com/article/wp-content/uploads/2015/01/article-2289562-187F97F8000005DC-947_634x482.jpg",
"title_text":"Take and Give",
"text_2":"Untuk beberapa alasan yang sulit dimengerti, alam telah membagi pria dan wanita dalam sebuah perbedaan sikap dalam memandang sebuah hal.",
"link_2/_text":"Men"
},
{"link_1/_text":"Women",
"text_1":"January 23, 2015",
"link_3":"http://pmj.astaga.com/article/?p=404",
"link_1":"http://pmj.astaga.com/article/?cat=71",
"link_3/_text":"10 Saran Bagi Wanita Untuk Menyatakan Cinta Lebih Dulu",
"text_list_1":["10 saran jika ingin menyatakan cinta","menyatakan cinta",
"menyatakan cinta kepada pria","menyatakan cinta lebih dulu",
"Mungkinkah Seorang Wanita Menyatakan Cintanya Lebih Dulu?|Matchmatter.com","wanita"],
"image_1":"http://pmj.astaga.com/article/wp-content/uploads/2015/01/secret-admirer.jpg",
"title_text":"10 Saran Bagi Wanita Untuk Menyatakan Cinta Lebih Dulu",
"text_2":"Apakah anda pernah menyukai seorang pria, dan dilihat dari gelagatnya sepertinya dia juga menyukai anda?"
}
],
"cookies":[],
"connectorVersionGuid":"ed0ce142-861e-4d2e-bacd-3dd1de491a69",
"connectorGuid":"d6d21746-2d8f-4980-b1ec-8e1a5d52b133",
"pageUrl":"http://pmj.astaga.com/article/?page_id=709"
}
But the problem is, i got more than one string to call the data, for example
"link_1/_text":"Reflection"
If i use this code i will got Just the URL and not title or content
<script>
var data = '$json_data';
$(data.results).each(function() {
var output = "<p>" + this.link_1 + "</p>";
$('#placeholder').append(output);
});
</script>
The point is, how to print results of Reflection
Can you help me for this code?
Thankyou

Using your syntax, you can use both jquery or javascript to iterate on the JSON.
var data = {---YOUR JSON...};
using JQuery
$(data.results).each(function () {
var output = "<div class='container'>";
output += "<p>" + this.title_text + "</p>";
output += "<p>" + this.text_1 + "</p>";
output += "<p>" + this.link_1 + "</p>";
output += "</div>";
$('#placeholder1').append(output);
});
using Javasscript
var d=document.getElementById("placeholder2");
var output="";
for (var i in data.results) {
output += "<div class='container'>";
for (var prop in data.results[i]) {
output += "<p>" + prop + " : " + data.results[i][prop] + "</p>";
}
output += "</div>";
}
d.innerHTML=output;
Here the JSFiddle example

You can use Jquery.parseJSON(). This will give you a js object which you can use to achieve what you want.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

You need to do something like this:
var json = [
{ "one": "1" },
{ "two": "2" },
{ "three": "3" }
];
$.each(json, function() {
$.each(this, function(name, value) {
/// do stuff
console.log(name + '=' + value);
});
});

Related

How to create tables in jQuery for $.each()

I am a beginner programmer that is trying to display data results I get from Etsy API into a table as shown below:
<tr><td>item.images</td><td><tr>item.title</tr><tr>item.price</tr></tr>
However, I am unable to display the results in a table and am having problems applying the solutions to my situation
Here is the set of working codes, and I have commented out my failed attempts.
<script type="text/javascript">
(function($){
$(document).ready(function(){
$('#etsy-search').bind('submit', function() {
api_key = "XXXXXXXXXXXXXXXXXXXXX";
terms = $('#etsy-terms').val();
etsyURL = "https://openapi.etsy.com/v2/listings/active.js?keywords="+
terms+"&limit=3&includes=Images:1&api_key="+api_key;
$('#etsy-images').empty();
$('<p></p>').text('Searching for '+terms).appendTo('#etsy-images');
$.ajax({
url: etsyURL,
dataType: 'jsonp',
success: function(data) {
if (data.ok) {
// Commented out are my failed attempt
//var table = "<table>";
$('#etsy-images').empty();
if (data.count > 0) {
$.each(data.results, function(i,item) {
$("<img/>").attr("src", item.Images[0].url_75x75).appendTo("#etsy-images").wrap(
"<a href='" + item.url + "'></a>"
//table+='<tr><td>'+item.title+'</td><td>'+item.price+'</td></tr>';
//}
);
// table+='</table>';
// $("#etsy-images").html( table );
if (i%4 == 3) {
$('<br/>').appendTo('#etsy-images');
}
});
} else {
$('<p>No results.</p>').appendTo('#etsy-images');
}
} else {
$('#etsy-images').empty();
alert(data.error);
}
}
});
return false;
})
});
})(jQuery);
</script>
<body>
<form id="etsy-search">
<input id="etsy-terms" size="32">
<button>Search!</button>
</form>
<div id="etsy-images"></div>
</body>
Additional info:
1. Currently the results looks like this:
After a successful search, the JSON results looks like this:
[
{
"listing_id": 123,
"state": "active",
"user_id": 123,
"category_id": 123,
"title": "XXX",
"price": "2.99",
"currency_code": "USD"
....
}
]
I eventually used trHTML to format the table:
var trHTML = '';
$('#etsy-table').empty();
$.each(data.results, function(i,item) {
trHTML += '<tr><td>' + '<a href="'
+ item.url +'" target="_blank" style="color: white"><img src="'
+ item.Images[0].url_75x75 + '" border="0"></a></td><td><tr>'
+ item.title + '</tr><tr>'
+ item.price + '</tr><tr><a href="'
+ vimg +'" target="_blank" style="color: white"><img class="autosizeImage"src="'
+ vimg + '" border="0"></a></tr></td></tr>';
})
$('#etsy-table').append(trHTML);
Firts step check the "crossdomain" someones browsers don't allow get data between different domains, you can enabled it with headers to allow than.

on change of div based drop down jquery

I have a drop down based on a JSON Object and the purpose of this to render a drop down box.
var Regions =
{
"ErrorInfo": {
"Success": true,
"ErrorCode": "",
"Program": "",
"Method": "",
"Message": "",
"Details": "",
"StackTrace": "",
"ErrorList": null
},
"Results": {
"DimName": "region",
"SubsetName": "",
"Members": [{
"ID": "CEurope",
"Name": "Central Europe",
"Children": [],
"Hierarchy": [],
"Attributes": []
},
{
"ID": "SEurope",
"Name": "Southern Europe",
"Children": null,
"Hierarchy": [],
"Attributes": []
}]
}
};
//var htmlStr = '';
var icount=0;
var mySelect = $('#options');
var optionsValues = '<select>';
$.each(Regions, function(){
optionsValues += '<option value="' + Regions.Results.Members[icount].ID + '">' + Regions.Results.Members[icount].Name + '</option>';
icount=icount+1;
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
This is my Javascript which is working but happy to refine the code so that I can learn the finer points of JS.
My HTML is like this
<!DOCTYPE html>
<html>
<head>
<title>JavaScript & jQuery - Chapter 13: Form Enhancement and Validation - Populate a selectbox</title>
<link rel="stylesheet" href="css/c13.css" />
</head>
<body>
<form name="howHeard" id="howHeard" action="/heard" method="post">
<div id="page">
</div>
<div id="options">
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/124.js"></script>
</body>
</html>
My question is how do I detect an on change event of my drop down list.
Any help would be appreciated as I learn through the maze of jquery javascript etc.
Cheerio
This should do it:
options.change(function() {
alert( "It changed!" );
});
ref: https://api.jquery.com/change/
Some refinement in your JS:
//var icount=0; ->Not needed
//var mySelect = $('#options'); ->Not needed
var optionsValues = '<select id="mySelect">';
$.each(Regions, function(index){
optionsValues += '<option value="' + Regions.Results.Members[index].ID + '">' + Regions.Results.Members[index].Name + '</option>';
//icount=icount+1;-> Not needed
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);
Basically for the above set-up, below code should work:
$("#mySelect").on('change',function(){
//do stuff here
});
Or if its dynamic element the below should definitely work:
$(document).on('change',"#mySelect",function(){
//do stuff here
});
UPDATE
WORKING DEMO TO CLARIFY YOUR DOUBTS
Bit more refinement on your JS:
var members=Regions.Results.Members; //Get all the members in a single variable
var optionsValues = '<select id="mySelect">';
//loop here for only member variables
$.each(members, function(index,value){
optionsValues += '<option value="' + value.ID + '">' + value.Name + '</option>';
});
optionsValues += '</select>';
var options = $('#options');
options.replaceWith(optionsValues);

Populating a table with an object with JQuery

I have an array of objects object [{Date, Count, City}]
Lets say I have this data
[{01/01/01, 10, New York}, {01/01/01, 15, London}, {01/01/01, 16, Rome},{02/01/01, 40, New York},{02/01/01, 25, London}, {02/01/01, 36, Rome}]
I want to populate an html table using JQuery and have the following result
Date | New York | London | Rome
01/01/01 | 10 | 15 | 16
02/01/01 | 40 | 25 | 36
Is it possible to generate a table similar to this with JQuery?
This is the code I have done so far
for (var i = 0; i < countResult.length; i++) {
var html = "<table><thead><tr><th>Date</th><th>City</th><th>Count</th></thead><tbody>";
for (var j = 0; j < countResult[i].length; j++) {
html += "<tr>";
html += "<td>" + countResult[i][j].date + "</td><td>" + countResult[i][j].city + "</td><td>" + countResult[i][j].count+ "</td>";
}
html += "</tr>";
html += "</tbody></table></br>";
$(html).appendTo("#div");
}
The solution for my question was:
var countResult = [
["01/01/01", 10, "New York"],
["01/01/01", 15, "London"],
["01/01/01", 16, "Rome"],
["02/01/01", 40, "New York"],
["02/01/01", 25, "London"],
["02/01/01", 36, "Rome"]
]
var cities = []
$.each(countResult, function(rowNum, row) {
var city = row[2];
if($.inArray(city, cities) < 0) cities.push(city);
});
var html = "<table><thead><tr><th>Date</th>"
+ $.map(cities, function (c) {
return "<th>" + c
}).join("") + "</tr></thead><tbody>";
var summary = {};
$.each(countResult, function
(rowNum, row) {
if(!summary[row[0]]) summary[row[0]] = {}
summary[row[0]][row[2]] = row[1];
});
$.each(summary, function (date, counts) {
html += "<tr><td>" + date;
$.each(counts, function (i, ct) {
html += "<td>" + ct ;
});
html += "</tr>";
});
$(html).appendTo("#div");
Try this code
var html='<table>';
var arObj = YOUR ARRAY OBJECT;
$(arObj).each(function(i, u) {
var Date = u[0];
var count = u[1];
var City=u[2];
html=html+'<tr><td>'+Date+'</td><td>'+count+'</td><td>'+City+'</td><td>';
});
html=html+'</table>';
Now append to html
$('#myDiv').append(html);

logic issue with spitting out data, variables being repeated

I am trying to parse out a table that has customers vertically and time stamps horizontally. what I have so far does this but repeats the time stamps from previous customers with each loop. Here is my code:
json = JSON.parse(xmlHTTP.responseText);
message = "<table><tr id='head_table'><td>Name:</td><td>Rnd 1:</td><td>Rnd 2:</td><td>Rnd 3:</td><td>Rnd 4:</td><td>Rnd 5:</td><td>Rnd 6:</td><td>Options:</td></tr>";
for(var i=0; i<json.collection.length; i++)
{
message = message + "<tr><td>" + json.collection[i].customer.name + "</td>";
for(var j=0; j<json.collection[i].events.length; j++)
{
eventmsg = eventmsg + "<td>" + json.collection[i].events[j].time_stamp + "</td>";
}
message = message + eventmsg + "</tr>";
}
message = message + "</table>";
The JSON looks like this:
- collection: [
- {
- customer: {
id: "1",
name: "Mr Jones",
customer_id: "1"
}
-events: [
-{
event_id: "1",
time_stamp: "1377083342"
}
-{
event_id: "2",
time_stamp: "1377083342"
}
I see no errors here try this .. if it does not work past part of the json.
var json = JSON.parse(xmlHTTP.responseText),
message = "<table><tr id='head_table'><td>Name:</td><td>Rnd 1:</td><td>Rnd 2:</td><td>Rnd 3:</td><td>Rnd 4:</td><td>Rnd 5:</td><td>Rnd 6:</td><td>Options:</td></tr>";
for(var i=0; i<json.collection.length; i++){
message+="<tr><td>" + json.collection[i].customer.name + "</td>";
for(var j=0; j<json.collection[i].events.length; j++){
message+="<td>" + json.collection[i].events[j].time_stamp + "</td>";
}
message+="</tr>";
}
message+="</table>";
you don't need to write msg=msg+evntmsg it's confusing and leads to errors
also you don't need another var for events one is enough as you just append
so msg+=newstring
think o it as you just append a string.
tip.: cache your json.
var collection = JSON.parse(xmlHTTP.responseText).collection
for(var i=0 , co ; co = collection[i] ; ++i){
message+="<tr><td>" + co.customer.name + "</td>";
for(var j=0 , ev ; ev = co.events[j] ; ++j){
message+="<td>" + ev.time_stamp + "</td>";
}
message+="</tr>";
}
message+="</table>";

JSON not working in Firefox but in Chrome and Safari it works as expected

I've a list that autopopulates from a JSON file:
<div class="conversionFormES" id="from1">
<label for="from">Convert From:</label>
<select size = "10" name="from" id="from" onchange="convertUnits()">
<option value="from">-Select an Option-</option>
<option value="from">Firefox</option>
</select>
</div>
I added the 'Firefox' option just to make sure something was being displayed and it is.
Any ideas what the problem could be. Just to re-iterate, it works perfectly with chrome and safari. Many thanks.
ConvertUnits function:
function convertUnits(){
var convertObj = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $("#from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(convertObj.units.val());
// convertObj.convertUnitsFromHash();
if(measurementType == "temp"){
convertObj.convertTemp();
}else{
convertObj.convertUnitsFromHash();
}
console.log('Measurement Type:', measurementType);
}
JSON Script called after the HTML Form.
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
</script>
EDIT: JSON sample:
{
"angle": [
{
"value": "degree",
"name": "Degree(deg)"
},
{
"value": "radian",
"name": "Radian(rad)"
}
]
}

Categories

Resources