I have the following json file which I want to show as a list.
[
{
"shopName": "The Coffee Connection",
"address": "123 Lakeside Way",
"phone": "16503600708",
"prices": [
{
"Cafe Latte": 4.75,
"Flat White": 4.75,
"Cappucino": 3.85,
"Single Espresso": 2.05,
"Double Espresso": 3.75,
"Americano": 3.75,
"Cortado": 4.55,
"Tea": 3.65,
"Choc Mudcake": 6.40,
"Choc Mousse": 8.20,
"Affogato": 14.80,
"Tiramisu": 11.40,
"Blueberry Muffin": 4.05,
"Chocolate Chip Muffin": 4.05,
"Muffin Of The Day": 4.55
}
]
}
]
I want to iterate over the prices and show them in in a listView. I am using the the following Ajax function and function to extract this data. Unfortunately when I run my code I have an empty list.
$.ajax({
type: 'GET',
url: '/data/hipstercoffee.json',
success: function(data) {
// console.log('success', data);
let widget = show(data);
$("#Meals").html(widget);
}
});
and my other function is.
$.ajax({
type: 'GET',
url: '/data/hipstercoffee.json',
dataType:'json',
success: function(data) {
var data = JSON.parse(data)[0];
// console.log('success', data);
let widget = show(data);
$("#Meals").html(widget);
}
});
I am getting unexpected o at JSON at position 1 error.
Your prices is an array with a single element (object). So you need to process this object. Something like this.
var data = [{
"shopName": "The Coffee Connection",
"address": "123 Lakeside Way",
"phone": "16503600708",
"prices": [{
"Cafe Latte": 4.75,
"Flat White": 4.75,
"Cappucino": 3.85,
"Single Espresso": 2.05,
"Double Espresso": 3.75,
"Americano": 3.75,
"Cortado": 4.55,
"Tea": 3.65,
"Choc Mudcake": 6.40,
"Choc Mousse": 8.20,
"Affogato": 14.80,
"Tiramisu": 11.40,
"Blueberry Muffin": 4.05,
"Chocolate Chip Muffin": 4.05,
"Muffin Of The Day": 4.55
}]
}];
function show(data) {
var ul = '<ul>' +
Object.keys(data[0].prices[0]).map(function(key) {
return '<li>' + key + ': ' + data[0].prices[0][key] + '</li>';
}).join('') +
'</ul>';
$('#result').html(ul);
}
show(data); //for demonstration purpose
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">loading...</div>
JSON is a string. You have to decode the it first to turn it into a javascript object. Also notice that an array [] is wrapped around the actual data object.
var data = JSON.parse(data)[0];
Tip: When retrieving data, always output it first (console.log(data)) in your success message, to see how the data is structured. You will spot things like the array much faster that way. Once your code is working, remove the output.
Related
The JSON Response I'm getting,
{
"user_data": {
"id": 22,
"first_name": xxx,
"last_name": xxx,
"phone_number": "123456789",
},
"question_with_answers" : [
{
"id": 1,
"question_name": "Features of our project that you like (select one
or more):",
"answers": [
{
"id": 19,
"question_id": 1,
"customer_id": 22,
"option": "Location",
},
{
"id": 20,
"question_id": 1,
"customer_id": 22,
"option": "Architecture",
},
]
},
{
"id": 2,
"question_name": "Features of our project that you DID NOT like
(select one or more):",
"answers": [
{
"id": 22,
"question_id": 2,
"customer_id": 22,
"option": "Location",
},
]
},
{
"id": 3,
"question_name": "How soon are you looking to buy a new home?",
"answers": [
{
"id": 24,
"question_id": 3,
"customer_id": 22,
"option": "Immediately",
}
]
}
]
}
So that is how JSON response looks like, now I need to display data using jquery
My js code
function openModal(Id){
var CustomerId = Id;
$.ajax({
type : 'get',
url: 'customer-details',
data: {
'CustomerId':CustomerId
},
success: function(data)
{
//what I have to do here
}
})
}
The output I want is,
first_name : xxx
last_name : xxx
phone_number : 123456789
1.Features of our project that you like (select one or more):
ans: Location, Architecture
2.Features of our project that you DID NOT like (select one or more)
ans: Location
3.How soon are you looking to buy a new home?
ans: Immediately
Thats how my output should look like from above json response,Is it possible to get above output using that Json response I got
There are two variable that I have passed from backend like user_data and question_with_answers
In success handler first of all make your json into a array using
var obj = JSON.parse(data);
Now in data you have array of your response and you can use this like
obj.first_name
obj.last_name
Note:- may be you have issue in JSON.parse so use first
var data = json.stringify(data)
after that use Json.parse function and use above data variable
this data
You have to set the dataType in the $.ajax call, set it to dataType:"json"...
After that, you got on the data variable in the success the json object and you can access it like data.user_data or data.id or data.first_name.
If you dont define the json as dataType, it will not work properly.
Addition
If you want to display the content of "question_with_answer" you have to iterate trough it, like ....
for (i in data.question_with_answer) { alert(data.qestion_with_answer[i]); }
I have json code that comes out like:
{
"player": [{
"player_id": "1",
"player_name": "Maxfly",
"player_image": "res_573fc05f57c0e.png",
"player_background_image": "images/player_backgrounds/581046687fd89.jpg",
"player_info": "",
"player_region": "North America",
"player_teams": [{
"id": "1",
"team_name": "Test Team",
"team_link": "test-team"
}, {
"id": "65",
"team_name": "Test Team 2",
"team_link": "test-team-2"
}]
}]
}
I've managed to get the player_id and player_name etc. My question is how to I just get the teams? I've tried the following:
$.getJSON("jsonlink",
function(data) {
$.each(data.player.player_teams, function(i,player_team){
var append_data = "<div class='item team_item'><div class='row'><div class='col col_img'><a href='/t/" + player_team.team_name + "' ></a></div></div></div>";
$("#popin-container").append($('<div>' + append_data + '</div>').hide().fadeIn(800));
});
});
Trying to figure out what I'm doing wrong. Is my json object correct?
Thanks!
Your data.player.player_teams is wrong, as data.player is an array, and not an object. You need to loop through it, or in simple way, you need to attach a [0] like this:
$.each(data.player[0].player_teams, function(i, player_team) {
I'm new with lodash but as the title states 'I'd like to push non-existing items inside an already declared object if they don't already exist' that is if I have
var lessdata = {
"id": 1004,
"name": "some event",
"bookmarked": false //not in moredata and I'd like to keep the var as is
};
var moredata = {
"id": 1004,
"name": "some event",
"time": { //from here
"hours": 2,
"minutes": 00,
"currency": "USD"
},
"place": "some place" //to here is new without '"bookmarked": false'
};
I'd like to have my result loaded back into the lessdata variable and have my result look like so
var lessdata = {
"id": 1004,
"name": "some event",
"time": {
"hours": 2,
"minutes": 00,
"currency": "USD"
},
"place": "some place",
"bookmarked": false
};
I stuck knowing know to use lodash apprpriatly in angular and wasnt sure if I need to use angualar's forEach or not.
I've dabbled with two approaches.
version 1
lessdata= _.uniq(lessdata, function(moredata) {
return moredata;
});
version 2
angular.forEach(lessdata, function(lkey, lvalue) {
console.log("[-]lessdata---lkey: " + lkey + ", lvalue: " + lvalue)
angular.forEach(moredata, function(mkey, mvalue) {
console.log("[+]moredata---mkey: " + mkey + ", mvalue: " + mvalue)
lessdata=_.uniq(lessdata, function(moredata) {
return moredata;
});
})
})
$scope.event = lessdata
Im assuming using _.uniq is the best approach? any help would be appreciated and I created a codepen here.
TLDR: just read the title
That's what lodash.defaults does:
Assigns own and inherited enumerable properties of source objects to the destination object for all destination properties that resolve to undefined.
lodash.defaults(lessdata, moredata);
So I'm having a problem accessing my json when its in a nested array. I previously had json set up like this with just one array and my .$each function worked perfectly. However I'm having trouble modifying it for this.
Json:
{
"tcontent": [{
"Name": "Septicaemia",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/septicaemia.jpg);'>",
"Variations": [{
"condition":"Community-acquired",
"organisms":"Staph. aureus",
"antimicrobial":"Flucloxacillin ",
"alternative":"(non anaphylaxis): ",
"comments": "Perform full septic screen."
}, {
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
}, {
"Condition":"Healthcare-associated",
"Organisms":"Varies",
"Antimicrobial":"Piperacillin",
"Alternative":"Seek advice from Consultant Microbiologist",
"Comments":"Always"
}]
}, {
"Name": "Infective Endocarditis (IE) (pending blood culture results)",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/endocarditis.jpg);'>"
}, {
"Name": "Central Nervous System Infections",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/cns.jpg);'>"
}, {
"Name": "Skin and Soft Tissue Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/skin.jpg);'>"
}, {
"Name": "Diabetic patients with foot infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/foot.jpg);'>"
}, {
"Name": "Bone and Joint Infections",
"url": "<a>",
"image":"<<div class='grid' style='background-image:url(img/anatomy/bone.jpg);'>"
}, {
"Name": "Intravascular Line Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/intravascular.jpg);'>"
}, {
"Name": "Urinary Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/urinary.jpg);'>"
}, {
"Name": "Respiratory Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/respiratory.jpg);'>"
}, {
"Name": "Gastrointestinal Infections",
"url": "<a>",
"image":"<div class='grid' style='backgroundimage:url(img/anatomy/gastrointestinal.jpg);'>"
}]
}
Here's my javascript to access it.
$(function (){
var imp = "Json/therapy.json"
$.getJSON(imp, function(data) {
var info = "<br>";
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
info += subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments
});
$(info).appendTo(".menu");
//alert(item)
};
});
});
});
I've tried a many variations on the var search but nothing seems to be working. I researched a lot of similar problems to this and I've been stuck on this for too long. Any light that can be shed on the situation would be much appreciated!
2 reasons why it doesn't work.
First of all javascript is case sensitive, Your variations differ.
subitem.condition fails on :
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
So change "Condition" to "condition", etc.etc.
second reason is the
Change $(info).appendTo(".menu"); to $(".menu").append(info);
Why?
$(".menu").append(info) Will just paste the string in the selected DOM element.
But you use
$(info)... and jquery does all kinds of fancy stuff now.
It tries to either use it as DOM selector, or create a new element.
Because your info starts with <br> $(info) tries to create a DOM element and it removes all text. Leaving just <br> because br cannot contain content.
Try to remove the initial <br> then you will see following error:
Uncaught Error: Syntax error, unrecognized expression:Community-acquiredStaph. aureusFlucloxacillin...
For example if you would type $("hahaha") , Jquery will try to find the tag <hahaha>, So when you remove the <br> your $(info) is looking for the tag <Community-acquiredStaph. aureusFlucloxacillin...>.
But because your string would then contain weird characters like "-()." It will fail. Hence the above error.
So you can only add html like this:
$("<span>hahah</span>").appendTo($(".menu"));
Or use selector
$("#myDiv").appendTo($(".menu"));
An example when $(info).appendTo(".menu"); working is:
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
var info = "<p>" + subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments + "</p>";
$(info).appendTo(".menu");
});
}
});
Using the following json:
http://pastebin.com/Bzpix1ai
I've read several examples of how to do what I want but none seem to work. I want to iterate over a JSON array but it's not working for me. When I look in chromes js console my data looks like this:
"[\r\n {\r\n \"EntryId\": 3,\r\n \"Title\": \"Tiny Living For sales\",\r\n \"Description\": \"This is a house for sale\",\r\n \"AddressViewModel\": {\r\n \"AddressId\": 3,\r\n \"Street1\": null,\r\n \"Street2\": null,\r\n \"City\": \"Los Angeles\",\r\n \"LocationId\": 5,\r\n \"LocationName\": \"California\",\r\n \"PostalCode\": null,\r\n \"Phone\": null,\r\n \"Latitude\": 34.052234,\r\n \"Longitude\": -118.243685\r\n },\r\n \"EntryCategoryName\": \"Houses for Sale\",\r\n \"EventStartDate\": null,\r\n \"EventEndDate\": null\r\n },\r\n {\r\n \"EntryId\": 2,\r\n \"Title\": \"Tiny Living Workshop\",\r\n \"Description\": \"This is a workshop\",\r\n ...
And if I turn it into an object by doing so:
var myObject = eval('(' + locations + ')');
It looks like this (formated):
[
{
"EntryId": 3,
"Title": "Tiny Living For sales",
"Description": "This is a house for sale",
"AddressViewModel": {
"AddressId": 3,
"Street1": null,
"Street2": null,
"City": "Los Angeles",
"LocationId": 5,
"LocationName": "California",
"PostalCode": null,
"Phone": null,
"Latitude": 34.052234,
"Longitude": -118.243685
},
"EntryCategoryName": "Houses for Sale",
"EventStartDate": null,
"EventEndDate": null
},
{
"EntryId": 2,
"Title": "Tiny Living Workshop",
...
But when I try to iterate over it (either the raw JSON or the object) it gives me each letter of the JSON, not each object in the array
for (var i = 0; i < myObject.length; i++) { console.log(myObject[i]); }
Like so:
"
[
\
r
\
Thanks
You evaluate the JSON and assign the result to "myObject", and then you attempt to iterate through "locations". It's no wonder that that doesn't work :-)
I figured it out. I was returning the JSON from my controller like this
return Json( jsonResults, "text/html");
I had to do this on a different controller to prevent IE from prompting the user to save the JSON results.
Anyways, that was putting quotes around the data so it wasn't being parsed correctly.
So I am now returning:
return Json( jsonResults);
Hopefully I don't have the IE problem (tested in 9 and didn't see it)