I've a json file to get a list of test results.
Below is the json file. And a short snippet of the jquery.
I am trying to get the test id from the json and display them as a unordered list.
How can I do that?
[
{
"Test":{
"id":"2949",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A",
}
},
{
"Test":{
"id":"2950",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A",
}
}
]
<script type="text/javascript">
$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
for (var i in data)
{
alert(data[i].[Test].id);
}
});
</script>
You're missing the quotes around Test, it should be a string and remove the dot before it.
alert(data[i]['Test'].id);
also your json is not valid, remove the trailing , after each book_type.
[
{
"Test":{
"id":"2949",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A"
}
},
{
"Test":{
"id":"2950",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A"
}
}
]
http://jsfiddle.net/ef7Nq/
Loop through the items in the array and append nodes for each id.
$.each(obj, function (i, item) {
ul.append($('<li>' + item.Test.id + '</li>'));
});
fiddle here
You can do data[i]['Test'].id or data[i].Test.id since there's no space in the name.
You can try this:
alert( data[i].Test.id );
Full Code:
$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
for (var i in data) {
alert( data[i].Test.id );
}
});
Demo
Try
Fiddle Demo
var ul = '';
for (var i in data)
{
ul += '<li>'+data[i]['Test'].id+'</li>';
}
$('#el').append($('<ul/>').html(ul));
Related
I have a JSON data and i want to list all attributes of class name inside divs and inner divs and tags.
Sample JSON DATA :
[
{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}
]
I have used children() but it is not taking inner class name, output i got is
main-header dark-bg row space-9 hide-md using the below code by taking json data in a variable
if($(t).children().length > 0){
console.log($(t).children().length);
//OUTPUT SHOWING 2
}
To achieve this you can use some relatively straightforward recursion to traverse down the DOM tree within the HTML string, something like this:
var data = [{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}]
function buildClassArray($el, arr) {
arr = arr || [];
$el.each(function() {
arr.push($(this).prop('class'));
$(this).children().each(function() {
buildClassArray($(this), arr);
})
});
return arr;
}
var classes = buildClassArray($(data[0].Field1));
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that if you want multiple classes on a single element to appear within their own entity in the array, simply split() the class string before you push it to the array:
var data = [{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}]
function buildClassArray($el, arr) {
arr = arr || [];
$el.each(function() {
arr.push(...$(this).prop('class').split(' '));
$(this).children().each(function() {
buildClassArray($(this), arr);
})
});
return arr;
}
var $el = $(data[0].Field1);
var classes = buildClassArray($el);
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a complex json string that looks like this:
{
"id":"2016666",
"dt":"2012",
"object_extends":[
{
"extend1":{
"id":"2016666",
"dt":"2012",
"active":"true",
"object_extend":[
{
"extend2":
{
"id":"2016666",
"secondary":null
},
"extend3":
{
"id":"2016666",
"pet":"willy"
}
}
]
}
}
]
}
Now i want to print this like a tree, but when searching for days i have to modify the json(which is not a option). How can i print this in a treeview? I tried for loops but each extend can have other attributes then other objects. Hope somebody can help me with this!
Can you check these out:
How to generate Treeview from JSON data using javascript
https://github.com/lmenezes/json-tree
https://github.com/liuwenchao/aha-tree
https://github.com/AlexLibs/niTree
https://github.com/tamirs9876/JSON.Tree.Builder -- one of my fav
I think visit this and use which you like:
https://github.com/search?utf8=%E2%9C%93&q=json+tree&type=Repositories&ref=searchresults
Edit For Your Request :
To remove the null nodes in https://github.com/tamirs9876/JSON.Tree.Builder -- one of my fav :
Cover line 8 with
if(data[i] != null){
}
in JsonTreeBuilder.js
Last state of js file is like
.
.
var ul = $('<ul>');
for (var i in data) {
var li = $('<li>');
if(data[i] != null){
ul.append(li.text(i).append(generateTree(data[i])));
}
}
.
.
I need to append this json data to an html element.
[
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
How to convert this easily using any plugin.Presently,I couldn't find any simple plugins in jquery,So please help me friends.
Thanks in advance..........
Hi you can use jPut jQuery Plugin (http://plugins.jquery.com/jput/)
Create a HTML jPut Template
<div jput="template">
{{website}}
</div>
<div id="main">
</div>
<script>
$(document).ready(function(){
var json=[{"website":"google","link":"http://google.com"},
{"website":"facebook","link":"http://fb.com"}];
$('#main').jPut({
jsonData:json, //your json data
name:'template' //jPut template name
});
});
</script>
jPut is easy to use comparing to normal parsing.
if there is lots of data to be appended it is very difficult to append using $.each loop.
in jPut just need to create template & to print the data just put the object name in {{}}.
With jQuery, you could do something like this:
data = $.parseJson(json);
$.each(data, function(key, obj) {
htmlElement = $(''+website+'');
$('body').append(htmlElement);
})
Why use a plugin for this? No need to write a plugin to go around this. Just simply loop it through & do what you wan't with the data. Here is an example:
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
var html = '';
$.each(data, function (index, item) {
html += '' + item.website + '';
});
$('body').append(html);
If you're expecting it to be an anchor tag then -
Html -
<div id="siteContainer"></div>
JS-
var sites = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
var $container = $('siteContainer');
$(sites).each(function(item, index){
var name = item['website'];
var link = item['link'];
var anchorTag = '' + name + '');
$container.appendTo(anchorTag);
});
NO need plugin, simply iterate with each function and append anchor tag with any selector tag.
var links = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
$.each(links, function(index, object){
$("<a></a>").attr("href", object.link).
text( object.website).css("margin", "5px").appendTo("body");
})
no plugin needed, can be done without jquery too
<div id="container">
</div>
<script>
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
document.getElementById('container').innerHTML = ''+data[0]['website']+' >> '+data[0]['link']+' <br> '+data[1]['website']+' >> '+data[1]['link']
</script>
LF way to short my js/jquery function:
$.ajax({ // Start ajax post
..........
success: function (data) { // on Success statment start
..........
//1. Part
$('var#address').text(data.address);
$('var#telephone').text(data.telephone);
$('var#mobile').text(data.mobile);
$('var#fax').text(data.fax);
$('var#email').text(data.email);
$('var#webpage').text(data.webpage);
//2. Part
if (!data.address){ $('p#address').hide(); } else { $('p#address').show(); };
if (!data.telephone){ $('p#telephone').hide(); } else { $('p#telephone').show(); };
if (!data.mobile){ $('p#mobile').hide(); } else { $('p#mobile').show(); };
if (!data.fax){ $('p#fax').hide(); } else { $('p#fax').show(); };
if (!data.email){ $('p#email').hide(); } else { $('p#email').show(); };
if (!data.webpage){ $('p#webpage').hide(); } else { $('p#webpage').show(); };
}, End Ajax post success statement
Here is my html:
<p id="address">Address:<var id="address">Test Street 999 2324233</var></p>
<p id="telephone">Telephone:<var id="telephone">+1 0000009</var></p>
<p id="mobile">Mobile:<var id="mobile">+1 0000009</var></p>
<p id="email">E-mail:<var id="email">info#example</var></p>
<p id="webpage">Web Page:<var id="webpage">www.example.com</var>/p>
How can we reduce the number of selector*(1. part)* and else if the amount (2. part)?
Assuming your object's property names exactly match the spelling of your element ids you can do this:
for (var k in data) {
$('var#' + k).text(data[k]);
$('p#' + k).toggle(!!data[k]);
}
...because .toggle() accepts a boolean to say whether to show or hide. Any properties that don't have a matching element id would have no effect.
Note: your html is invalid if you have multiple elements with the same ids, but it will still work because your selectors specify the tag and id. Still, it might be tidier to just remove the ids from the var elements:
<p id="address">Address:<var>Test Street 999 2324233</var></p>
<!-- etc. -->
With this JS:
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
And then adding some code to hide any elements that aren't in the returned data object:
$('var').parent('p').hide();
...and putting it all together:
$.ajax({
// other ajax params here
success : function(data) {
$('var').parent('p').hide();
for (var k in data) {
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
}
}
});
Demo: http://jsfiddle.net/z98cw/1/
["address", "telephone", "mobile", "fax", "email", "webpage"].map(
function(key) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show();
} else {
$('p#' + key).hide();
}
});
But you should not.
As long as the properties of the object match the id attributes of the p tags you can iterate through the object using the property name as a selector. Also since id attributes are unique, refrain from prefixing the selector with var it is unnecessary.
var data = {
address: "address",
telephone: "telephone",
mobile: "mobile",
fax: "fax",
email: "email",
webpage: "webpage"
};
for(x in data){
var elem = $("#" + x);
if(elem.length == 1){
elem.text(data[x]);
}
}
JS Fiddle: http://jsfiddle.net/3uhx6/
This is what templating systems are created for.
If you insist on using jQuery there is a jQuery plugin: https://github.com/codepb/jquery-template
More:
What Javascript Template Engines you recommend?
I would use javascript templates for this (I've shortened the example a quite a bit, but you should get the gist).
First the template, I love Underscore.js for this so I gonna go ahead and use that.
<% if data.address %>
<p id="address">Address: {%= Test Street 999 2324233 %}</p>
to compile this inside your success function
success: function(data) {
//assuming data is a json that looks like this {'address':'my street'}
var template = _.template(path_to_your_template, data);
$('var#addresscontainer').html(template);
}
Thanks for birukaze and nnnnnn:
With your advice came function;) :
for (var key in data) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show().find('var').text(data[key]);
} else {
$('p#' + key).hide();
}
};
Now i can avoid for selector with var.
I need to parse the following example XML in jquery, to get the attribute "V"
XML file:
<RES>
<R N="1">
<MT N="myMeta1" V="myMeta1Value"/>
<MT N="myMeta2" V="myMeta2Value"/>
<MT N="myMeta2" V="myMeta2Value"/>
</R>
</RES>
And my javascript is the following:
function(data){
$(data).find('R').each(function(){
var $result = $(this);
$result.find('MT').each(function(_mt) {
console.log($(_mt).attr("V") );
});
});
}
I get undefineds, what am I doing wrong?
The first argument to .each callback is the index, the second one is the value. You can also use this:
$result.find('MT').each(function() {
console.log($(this).attr("V") );
});
Or:
$result.find('MT').each(function( index, _mt ) {
console.log($(_mt).attr("V") );
});
You are using index as an element in each. As first parameter is index pass two parameter in each and use the second to get the element.
function(data){
$(data).find('R').each(function(){
var $result = $(this);
$result.find('MT').each(function(_mt, obj) {
console.log($(obj).attr("V") );
});
});
}