I'm new one to work with JSON and getting stuck that how to call JSON data from nested .json file. please check the code below ...
JSON FORMAT
{
"hotels": {
"category": [{
"name": "Exotic and Luxurious",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
},{
"name": "In the Tourist Hub",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
},{
"name": "Close to the Beach and Market",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
},{
"name": "Private and Peaceful",
"products": [{
"name": "Sofitel L'Imperial Resort and Spa",
"budget": "Luxery",
"location": "flic en flac",
"price": "71500"
}, {
"name": "Shanti Maurice a Nira Resort",
"budget": "Luxery",
"location": "Chemin Grenier",
"price": "88500"
}]
}]
}
}
AJAX CODE
jQuery(document).ready(function() {
jQuery.ajax({
url: 'hotels.json',
type: 'GET',
dataType: 'json',
success : function(data){
/*jQuery(data).each(function(index, value){
console.log(value.hotels.name);
})*/
//console.log(data.hotels.category[1].name);
//alert(JSON.stringify(data));
var i = 0;
jQuery(data.hotels.category).each(function(){
jQuery('.theme ul').append('<li data-role="'+data.hotels.category[i].name+'">'+data.hotels.category[i].name+'</li>');
i++;
})
jQuery(data.hotels.category).each(function(){
jQuery('.budget ul').append('<li data-role="'+data.hotels.category[i].name.products[0].name+'">'+data.hotels.category[i].name.products[0].name+'</li>');
i++;
})
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
HTML
<div class="theme">
<p>Hotel experience theme</p>
<ul>
</ul>
</div>
<div class="budget">
<p>Budget</p>
<ul>
</ul>
</div>
I want to call name data from products which is defined in category in <li> of budget div
Change:
jQuery(data.hotels.category).each(function() {...});
to:
jQuery.each(data.hotels.category, function() {...});
The first form is for looping over DOM elements in a selection, the second form is for looping over Javascript arrays and objects.
And within the function, you can use this to refer to the element, you don't need to use data.hotels.category[i].
But if you continue to use data.hotels.category[i], you need to set i back to 0 before the second loop. Or you could just do everything in one loop. And .each() passes the array index to the function, so you don't need your own variable.
Finally, products is not a sub-property of the name property.
The final result of fixing and simplifying this should be:
jQuery.each(data.hotels.category, function(){
jQuery('.theme ul').append('<li data-role="'+this.name+'">'+this.name+'</li>');
jQuery('.budget ul').append('<li data-role="'+this.products[0].name+'">'+this.products[0].name+'</li>');
});
The products belong to category directly so you don't have to pass by name to get it, you should go directly to it, so try to replace :
data.hotels.category[i].name.products[0].name
BY :
data.hotels.category[i].products[0].name
Hope this helps.
Related
I tried several approches and none of them works. I think this is because I am using JSON returned by django DRF.
I want to create a list of IFSC using this JSON in Jquery in my HTML template itself.
This is how my api returns JSON for any queryset.
{
"count": 134,
"next": "http://127.0.0.1:8000/api/bankdetailapi/?limit=5&offset=5&q=ABHY",
"previous": null,
"results": [
{
"ifsc": "ABHY0065001",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "RTGS-HO",
"address": "ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065002",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "ABHYUDAYA NAGAR",
"address": "ABHYUDAYA EDUCATION SOCIETY, OPP. BLDG. NO. 18, ABHYUDAYA NAGAR, KALACHOWKY, MUMBAI - 400033",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065003",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "BAIL BAZAR",
"address": "KMSPM'S SCHOOL, WADIA ESTATE, BAIL BAZAR-KURLA(W), MUMBAI-400070",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
}
]
}
The code I tried:
$(document).ready(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = `IFSC: ${data.ifsc}`
})
)}
It throws error in browser console that Uncaught ReferenceError: text is not defined . I want to use this IFSC list as autocomplete suggestions.
$("#q").keyup(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = ['']
for (var i=0;i<data.results.length;++i){text.push(data.results[i].ifsc)}
// var text = `IFSC: ${data.results.ifsc}`
console.log(text)
By using push method and iterating on whole data i managed to get list of all IFSC values.
I'm looking to convert each 'item'(from JSON) to appear inside a section(or div) with the image and its link appearing with the name, id, and price - how would this be done with jQuery. jQuery and JSON are below, I don't currently have any classes in the HTML other than 'placements-title' for the header and 'placements-items' for the section.
Current jQuery:
$.ajax({
type: 'GET',
url: 'pathtoJSONdata.json',
dataType: 'json',
success: function (data) {
$(".placements-title h2").append(data.placements[0].message);
$(".placements-items").append(data.placements[0].items[1].id);
}
});
Use a loop build the html as a string and append it to your desired dom element
var data = {
"placements": [{
"message": "If you like this, you might be into these",
"items": [{
"id": "029148",
"name": "Woodblock Play Suit",
"linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/woodblock-play-suit/029148.html",
"imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw0f93fcd4/images/hi-res/warehouse_02914899_2.jpg",
"price": "46.00"
},
{
"id": "0294526806",
"name": "Smock Dress",
"linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/smock-dress/0294526806.html",
"imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dwc9d5ea05/images/hi-res/warehouse_02945268_5.jpg",
"price": "39.00"
},
{
"id": "0297180006",
"name": "Cami",
"linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/cami/0297180006.html",
"imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4b954022/images/hi-res/warehouse_02971800_2.jpg",
"price": "9.00"
},
{
"id": "0298473606",
"name": "Asymmetric Wrap Cami Dress",
"imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw686fea84/images/hi-res/warehouse_02984736_2.jpg",
"price": "46.00"
},
{
"id": "0297155306",
"name": "Casual Stripe Tee",
"linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/casual-stripe-tee/0297155306.html",
"imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4609af3e/images/hi-res/warehouse_02971553_2.jpg",
"price": "16.00"
}
]
}]
}
$.each(data.placements[0].items,function(i,v){
$('body').append('<img src="'+v.imageURL+'" height="50" width="50"><div class="placements-title"><a href="'+v.linkURL+'"><h2>'+v.name+'</h2>'+v.price+'</div>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
hoping to use randomuser.me in a prototype i'm putting together (html, css, jquery)
I need to use its api to access profile photos.
I've got this code puling in the JSON as they show in their documentation:
$.ajax({
url: 'https://randomuser.me/api/?results=5&gender=female',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
Now I need to get the url from the picture value in the JSON and write it to the background-image css of a group of divs...I imagine by creating some kind of loop, anybody have an easy to understand way of doing this?
the JSON returned looks like this:
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "romain",
"last": "hoogmoed"
},
"location": {
"street": "1861 jan pieterszoon coenstraat",
"city": "maasdriel",
"state": "zeeland",
"postcode": 69217
},
"email": "romain.hoogmoed#example.com",
"login": {
"username": "lazyduck408",
"password": "jokers",
"salt": "UGtRFz4N",
"md5": "6d83a8c084731ee73eb5f9398b923183",
"sha1": "cb21097d8c430f2716538e365447910d90476f6e",
"sha256": "5a9b09c86195b8d8b01ee219d7d9794e2abb6641a2351850c49c309f1fc204a0"
},
"dob": "1983-07-14 07:29:45",
"registered": "2010-09-24 02:10:42",
"phone": "(656)-976-4980",
"cell": "(065)-247-9303",
"id": {
"name": "BSN",
"value": "04242023"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/83.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/83.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
"nat": "NL"
}
],
"info": {
"seed": "2da87e9305069f1d",
"results": 1,
"page": 1,
"version": "1.1"
}
}
If I've got right you need something like this:
$( ".myDivClass" ).each(function( index ) {
$( this ).attr("background-image", results[index].picture.medium));
});
Or if you have in results only one element of array so to do: ...results[0].picture.medium...
I hope someone can help me with this issue I have. What I want is a select box, which is getting filled from a json file. The problem is I have a strange kind of json file which I dont know if its array or object.
Here is how it loosk like:
{
"Id": 4,
"Name": "Testing Demo",
"OpeningHours": [
{
"Name": "Monday",
"Hours": "Kl. 09:30:00 - 21:00:00"
}
],
"Address": {
"Street": "Johnson road",
"StreetNumber": "5",
"Town": "London"
},
"Phone1": "4123213414",
"Phone2": null,
"Documents": null,
"Messages": [
{
"Title": "We are on the way",
"Body": "fine",
"Created": "01-02-2014"
},
{
"Title": "Get the stuff",
"Body": "To be ready",
"Created": "01-01-2014"
}
],
"Employees": [
{
"Name": "John Hood",
"Description": "officer",
"ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
},
{
"Name": "John hood 2",
"Description": "athletic",
"ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
}
]
}
How Iam going to show values of ID and the name?
This code it doesnt work which I dont know if Iam doing it even correctly..
(function($) {
$(document).ready(function() {
$('<tr class="form-field form-required"></tr>').append(
$('<th scope="row">New field</th>')
).append(
$('<td></td>').append(
$('<select id="release-list"></select>')
).append(
$('<p>Explanation about your new field</p>')
)
).insertAfter('#wpbody-content table tr:eq(2)');
});
$.getJSON('../../cache/path.json', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
$('<option/>').attr('value', val[key]["Id"]).html('value' + val[key]["Name"]).appendTo(select);
});
});
})(jQuery);
you can convert the data from json to array using JSON.parse()
http://www.dyn-web.com/tutorials/php-js/json/parse.php
Example:
var data = '{"first":[1,2,3],"second":[4,5,6]}';
var jsonData = JSON.parse(data);
alert(jsonData.first[1]);
alert(jsonData.second);
Can you please take a look at This Demo and let me know how to access to JSON object like credit which is declared inside the same requester script as:
var credit = [{
"name": "John Johnson",
"street": "Oslo West 16",
"phone": "222 7894562"
}, {
"name": "Davie Amber",
"street": "Alberta 52",
"phone": "555 1234567"
}, {
"name": "Marck William",
"street": "Delestre 125",
"phone": "666 7254599"
}];
$("button").click(function () {
$.ajax({
url: "credit",
success: function (result) {
$("#div1").html(result);
}
});
});
I know in real world, there is no need to do this since is doable in simple JavaScript but for doing a specific test I need to provide the test environment like this which is running by $.ajax() method.
Thanks
mockjax might be what you looking for.
Here is your example with some tweaks to get it to output to the div (doesn't work in chrome for me because of the mockjax script mime type)
Html
<div id="div1"></div>
<button>Get Data</button>
Javascript
$(document).ready(function () {
$.mockjax({
url: '/someurl',
responseText: [{
"name": "John Johnson",
"street": "Oslo West 16",
"phone": "222 7894562"
},
{
"name": "Davie Amber",
"street": "Alberta 52",
"phone": "555 1234567"
},
{
"name": "Marck William",
"street": "Delestre 125",
"phone": "666 7254599"
}]
});
$("button").click(function () {
$.ajax({
url: "/someurl",
success: function (result) {
console.log(result);
$("#div1").html(JSON.stringify(result));
}
});
});
});