JavaScript failing parsing JSON - javascript

I need to filter some information. The information is coming from a JSON parse. I can't make it work. What I want is that the JSON is filtered into the HTML classes. I think I'm stupid
$.ajax({
// Agenda
type: 'POST',
url: 'agendas',
data: {results: 'events'},
dataType: 'json',
cache: false,
success: function (response) {
$('.date, .country, .events').html('');
$.each(response.results, function (index, result) {
if (result.status)
$('.date').append(result.server);
$('.country').append(result.server);
$('.events').append(result.server);
});
}
});
It would be lovely if someone could help me
JSON:
{
"results": [
{
"events": {
"id": 1,
"date": "2022-05-06T00:00:00+00:00",
"description": "test",
"time": "2017-02-03T06:40:00+00:00",
"location": "NL",
"year": "2008",
"event": "Idk"
}
},
{
"events": {
"id": 2,
"date": "2019-04-05T00:00:00+00:00",
"description": "aasdasdasda",
"time": "2017-02-03T15:04:00+00:00",
"location": "asdasdasd",
"year": "0000",
"event": "asdasd"
}
}
]
}
HTML:
<div class="day">
<h2 class="date">Januari 23</h2>
<div class="country-events">
<span class="country">UK</span>
<div class="events">
<span class="event">Conference Amsterdam<br />11:00 CET</span>
<span class="event">Webinar Copenhagen<br />15:00 CET</span>
</div>
</div>
I really can't get my head around this. I know it is not the correct code, I am new to JSON and JavaScript. 4th day currently so please forgive me.
Thank you in advance
UPDATE
This is what it shows currently, the data from the json file needs to go in the specific elements

$.each(response.results, function(index, result) {
console.log(result)
$('.date').append(result.events.date);
$('.date').append('</br>');
$('.country').append(result.events.location);
$('.country').append('</br>');
$('.events').append(result.events.event);
$('.events').append('</br>');
});
is this what you want?
https://plnkr.co/edit/wCYJPXgAPII1mcW4cKw7?p=preview
check this fiddle

Related

Issues adding sessions and information to the Google Fit REST Api using JS

So I am reasonably new to using API's with Js but I am struggling a lot to understand how the Google Fit API works. I am attempting to add a new Workout's data to the API by adding a session and some data for the intensity (heart points) of the session. I can get the session to appear correctly but run into constant errors when I try to create a dataSource and add a point to it for the session. It would be greatly appreciated if someone could help me to fix my code to achieve this or could direct me to a more thorough example of similar code as the API docs don't seem to be too well detailed with examples etc. Thanks in advance.
Here's the 3 api calls that I have written so far, one for creating the DataSource, one for the DataPoint and one for the Session. The session works correctly and adds a session of 1 hr for the correct activity but I am unable to get any of the other API requests to work.
Data Source :
``gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {"field":[{
"format": "floatPoint",
"name": "com.google.heart_minutes"
}],
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000019",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
``
Data Point :
``
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:292824132082:op:6:1000019",
"userId": "me",
"datasetId": "1592087806561000000-1592287806561000000",
"resource": {
"minStartTimeNs": "1592087806561000000",
"maxEndTimeNs": "1592287806561000000",
"dataSourceId": "raw:com.google.heart_minutes:292824132082:op:6:1000019",
"point": [
{
"startTimeNanos": "1592087806561000000",
"endTimeNanos": "1592287806561000000",
"value": [
{
"fpVal": 89.1
}
],
"dataTypeName": "com.google.heart_minutes"
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
``
Session :
``gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": "someSessionId19",
"id": "someSessionId19",
"name": "Awesome Workout19",
"description": "A very intense workout",
"startTimeMillis": new Date().getTime() - 3600000,
"endTimeMillis": new Date().getTime(),
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": 3600000
}).then((res) => {console.log(res)});
console.log('res')
//request.execute((res) => {console.log(res);console.log('executrd')})
console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
var request2 = gapi.client.fitness.users.sessions.list({
"userId":"me"
}).then((res) => {console.log(res)})
``
Error message
{message: "Unable to fetch DataSource for Dataset: raw:com.google.heart_minutes:292824132082:op:6:1000019", domain: "global", reason: "invalidArgument"}
It looks like it could be that you're trying to pass in the wrong fields for the data type: if you want to use a standard data type (like com.google.heart_minutes), you should either pass the exact fields of the standard data type (the field should be called "intensity"); or just pass the data type name, and the backend will fill them in for you.
So, if you change the data type to
"dataType": {"name": "com.google.heart_minutes"}
It should work.
Then, you need to use the data source ID returned from that request for the data points.
Awesome, so after some support in the comments I have some working code to add a new session with data from a previously defined data source using 3 API calls. The first call is to create a data source and only needs to be run once. The second and third then add a data point to a data set and creates a new session for the workout respectively. Here's the final working code:
Data Source:
/*
gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000020",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
*/
Data and Data Set:
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:108881196053:op:6:1000020",
"userId": "me",
"datasetId": z,
"resource": {
"minStartTimeNs": workoutStartTime * 1000000,
"maxEndTimeNs": workoutEndTime * 1000000,
"dataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"point": [
{
"originDataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"value": [
{
"fpVal": 8
}
],
"dataTypeName": "com.google.heart_minutes",
"endTimeNanos": workoutEndTime * 1000000,
"startTimeNanos": workoutStartTime * 1000000,
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
Session:
gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": id,
"id": id,
"name": "Morning Workout",
"description": "A very intense workout",
"startTimeMillis": workoutStartTime,
"endTimeMillis": workoutEndTime,
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": workoutEndTime - workoutStartTime
}).then((res) => {console.log(res)});
console.log('res')

How to extract a JSON object from the resulting JSON array? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
I have the following code to get the results of a query. The query results are in the form of JSON.
$.ajax({
url: ..... //url//...,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
"type": "daysofyear",
"entity": {
"year": "2015"
}
}),
type: "POST",
dataType: "json",
success: function(result) {
if ((result) && (result.isSuccess == true)) {
alert("SUCCESS");
alert(json.entity.day);
}
},
});
The returned JSON is:
{
"isSuccess": true,
"results": [{
"jsonClass": "RuleSuccess",
"message": "Found mapping for year: 2015",
"rule": {
"name": "Year rule",
"metadata": {}
},
"entity": {
"year": "2015",
"month": "December",
"day": "Saturday"
}
}]
}
Im basically trying to extract the value of month, year, day separately and display them alone using
alert(json.entity.day);
Please advice.
Update
var a =JSON.parse('{"isSuccess":true,"results":[{"jsonClass":"RuleSuccess","message":"Found mapping for year: 2015","rule": {"name":"Year rule","metadata":{}}, "entity":{"year":"2015", "month":"December", "day":"Saturday"}}]}') ;
alert(a.results[0].entity.day);
Original
Use
alert(result[0].rule.entity.day);
try this:
obj = JSON.parse(json);
console.log(obj[0].rule.entity.day);

How get first image from all posts with ajax

I have this code which spits out all the content for the first post only. I would like it to spit out the first image from all posts.
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
$(".x").html(postBody);
}});
And this is a ajax response:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": { ... },
"posts": [
{
"blog_name": "citriccomics",
"id": 3507845453,
"post_url": "http:\/\/citriccomics.tumblr.com\/post\/3507845453",
"type": "text",
"date": "2011-02-25 20:27:00 GMT",
"timestamp": 1298665620,
"state": "published",
"format": "html",
"reblog_key": "b0baQtsl",
"tags": [
"tumblrize",
"milky dog",
"mini comic"
],
"note_count": 14,
"title": "Milky Dog",
"body": "<p><img src=\"http:\/\/media.tumblr.com\
/tumblr_lh6x8d7LBB1qa6gy3.jpg\"\/><a href=\"http:\/\
/citriccomics.com\/blog\/?p=487\" target=\"_blank\">TO READ
THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired by
something <a href=\"http:\/\/gunadie.com\/naomi\"
target=\"_blank\">Naomi Gee<\/a> wrote on twitter, I really
liked the hash tag <a href=\"http:\/\/twitter.com\/
search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
and quickly came up with a little comic about it. You can
(and should) follow Naomi on twitter <a href=\"http:\/\
/twitter.com\/ngun\" target=\"_blank\">#ngun<\/a> I'm on
twitter as well <a href=\"http:\/\/twitter.com\
/weflewairplanes\"target=\"_blank\">#weflewairplanes<\/a>
<\/p>\n\nAlso, if you’re a Reddit user (or even if
you're not) I submitted this there, if you could up vote
it I'd be super grateful just <a href=\"http:\/\
/tinyurl.com\/5wj3tqz\" target=\"_blank\">CLICK HERE<\/a>"
},
...
],
"total_posts": 3
}
}
As you can see, images in the body are wrapped with tags.
How i get the images?
Using jQuery, see the sample code:
$(results.response.posts[0].body).find('img').first();
It is probably not the best alternative, but it should do.
If you wanna do it for multiple posts use array of images:
var img = new Array();
$.each(results.response.posts, function (ix,el){
img.push($(el.body).find('img').first());
})
try this:
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
var html = $(postBody);
var firstImage = $(postBody).find("img:first");
}});
var $ct = $('.x');
$.ajax({
url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function (results) {
console.log(results);
$.each(results.response.posts, function (_, post) {
$(post.body).find('img:first').appendTo($ct)
})
}
});

jQuery inserting JSON value to element with specific class

I'm have a little trouble with some jQuery I have been trying to put together today.
Basically what I am trying to achieve is to dynamically have prices inserted into a price button on my page by reading from a JSON feed.
The idea is that there is an empty span that will contain the price. I have given all of the price spans the class .getPriceNew. Each span also has an id which is equal to the SKU number for the item like this <span class="getPriceNew" id="123456"></span>.
The mechanic is that for each span that has the class .getPriceNew the JSON will be queried for the information with the SKU id used as part of the query string.
Here is an example of the code i have tried
jQuery
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
HTML
<span class="getPriceNew" id="123456"></span>
<span class="getPriceNew" id="789123"></span>
<span class="getPriceNew" id="456789"></span>
<span class="getPriceNew" id="654321"></span>
JSON Example
This is what a single item from the JSON feed would look like - I have filtered it a little
/api/MyApi.svc/GetProductBySku/123456
Updated with valid JSON
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://someurl.com/productImages/assets/img//icon18.gif"
},
"Barcode": {
"Barcode": "5026555408684"
},
"Description": "HTML",
"Id": 12214,
"Packshots": [
"http://someurl.com/productImages/914383/1min.jpg",
"http://someurl.com/productImages/914383/2med.jpg",
"http://someurl.com/productImages/914383/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Format",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Product Title",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Take Two Interactive Software"
},
"VideoHTML": "HTML",
"status": {
"Response": "product found",
"Success": true
}
}
I would love some help on this as I am really scratching my newbie head at this stage. I have managed to have console.log output the prices to the log but when I try and insert them back into the spans all I get is [object] [Object].
You are doing
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
getJSON returns a jqXHR object, which is not what you need. Try this:
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
// Save a refference to this span.
var thisSpan = $(this);
$.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
// Request complete, NOW we can use the data we got!
thisSpan.html("€"+data.Variants[0].Price);
});
})
The callback is where you want to use the data you get from your AJAX calls. All AJAX methods ($.ajax, $.get, $.post, $.getJSON, etc) will return a jqXHR object.
I think your javascript code is correct but your Json output has two errors:
1: "Description":"Some HTML Description here, <- you forgot the closing quote
2: "ID":0}, <- delete the closing brace
So your Json will result like this:
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://url.com/image.gif"
},
"Barcode": {
"Barcode": "4876416541647"
},
"Description": "Some HTML Description here",
"Id": 12214,
"Packshots": [
"http: //url.com/productImages/914383/1min.jpg",
"http: //http: //url.com/2med.jpg",
"http: //http: //url.com/3max.jpg"
],
"ID": 0,
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Titleoftheproduct",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Vendorname"
},
"VideoHTML": "<iframewidth="725"height="408"src="http: //www.youtube.com/embed/videoseries?list=PLofwA47XDv2_KnfUY52_8mlWg0iUEv8ci"frameborder="0"allowfullscreen></iframe>",
"status": {
"Response": "productfound",
"Success": true
} }
now your code
data.Variants[0].Price
will return 49.97
to validate Json you can paste it into http://jsonlint.com/ i think is very useful
Hope this helps

JSONP Object Error

I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?
This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.

Categories

Resources