Finding JSON key match with jQuery and PokéAPI - javascript

I'm trying to find and use an english translation of a language JSON endpoint using the PokéAPI in an app I am developing. I need to utilise translations when submitting a call to one of the urls shown below. Unfortunately, the english language key is not always in the same order in the array response so I need a way of finding and checking for it so that the correct english translation is shown on the front-end.
Im trying to retrieve:
flavor_text_entries[X].language.en key in each search and retrieve the flavor_text_entries[X].flavor_text to show the description on the front-end.
API URL 1:
https://pokeapi.co/api/v2/pokemon-species/3/
API URL 2:
https://pokeapi.co/api/v2/pokemon-species/10/
Code:
var pokeBio = $("[data-poke-bio]").html();
function submit(){
var pokeID = $("[data-poke-id]").val();
var pokeSpecURL = "https://pokeapi.co/api/v2/pokemon-species/" + pokeID;
$.ajax({
type: "GET",
url: pokeSpecURL,
success: function(dataSpec){
ajaxSpecSuccess(dataSpec);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
ajaxError();
}
});
}
function ajaxSpecSuccess(dataSpec){
var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;
var pokeBio = $("[data-poke-bio]").html(pokeMatchBio);
}
Snippet I need to manipulate:
var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;

Step 1, find the english entry
Step 2, display its flavor_text or a message if it wasn't found
let englishEntry = dataSpec.flavor_text_entries.find(entry => entry.language && entry.language.name && entry.language.name === 'en');
if (englishEntry) {
console.log(englishEntry.flavor_text);
} else {
console.log("English entry not found");
}

Related

How to print JSON array with AJAX call in a pretty format for UI

I am trying to validate data in a modal. If there is an error, an alert box is displayed. I am getting the output of the API in this format:
[{"Column":"ReportId","Result":"Invalid","Value":"repTest"},
{"Column":"Category","Result":"Invalid","Value":"testing"}]
I want to make it more readable to the user. How to get an output something like this in the alert box:
ReportId is invalid due to repTest
Category is invalid due to testing ( or any custom string between the corresponding values)
$.ajax({
type: 'POST',
url: 'validate_report',
contentType: 'application/json',
data: JSON.stringify(AddreportRepoFinalObj),
success: function (data) {
if(data.indexOf('Failure') > -1){
var e=JSON.stringify(data);
pwIsf.alert({msg:'Failure'+e ,type:'error'});
}
else if(data.indexOf('Success')>-1)
{
document.getElementById('btn_addUpdate').removeAttribute('disabled')
pwIsf.alert({msg:'Valid',type:'info'});
$(validAddRepbtn).off();
}
else{
var a=data; // I want to access the value part here from the data. Like I want to get rcaReportID, Invalid and repTest only and not column result and value
pwIsf.alert({msg:a, type:'error'});
}
},
})
Assuming that data in the final if condition in your example is a JSON string then you first need to parse it to an array of objects. From there you can loop through it and build your string output:
let data = '[{"Column":"ReportId","Result":"Invalid","Value":"repTest"},{"Column":"Category","Result":"Invalid","Value":"testing"}]'
let arr = JSON.parse(data);
var message = arr.map(o => `${o.Column} is ${o.Result} due to ${o.Value}`).join('\r\n');
console.log(message);

How do I loop through data using ajax and mysql

We got a project for school were i need to create an mp3 album playlist using a premade PHP api using javascript or jquery only (Not allowed to use php).
I can enter the data using an ajax call.
I need to be able to enter more than one song with its url.
I managed to enter the data this way to the DB into a column named songs.:
[{"name":["song1","song2"],"url":["url1","url2"]}]
How do I loop through this using Javascript or jQuery and showing it as a list?
This is the ajax call I am using.
function getsongs(index, name, url){
$.ajax({
url: "api/playlist.php?type=songs&id=" + index,
method: 'GET',
data: {
"songs": [
{
"name": name,
"url": url
},
] },
success: function(response, playlist){
// Need to loop here?
},
error: function(xhr){
console.log('error')
console.log(xhr)
}
}); }
Thank you.
You can use "for" :
var arr = [{"name":["song1","song2"],"url":["url1","url2"]}];
var names = arr[0].name; // extract names from arr
var urls = arr[0].url; // extract urls from arr
for(var i=0; i< names.length && i < urls.length; i++){
console.log(names[i]);
console.log(urls[i]);
}

How do I access a certain string variable in a json API?

I am using the weatherunderground api, and I would like to access the forecast only for today. I usually use parsed_json[][] until I get the variable I need, but in this case there is an array. Here is my code:
function findWeather() {
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/c531e176f43b999d/forecast/q/CT/Old_Greenwich.json",
dataType : "jsonp",
success : function(parsed_json) {
var forecasts = parsed_json['forecast']['txt_forecast']['forecastday: 0']['fcttext'];
var forecastString = "The weather is" + forecasts + "."
speak(" test" + forecastString);
}
});
});
}
function speak(x) {
var msg = new SpeechSynthesisUtterance(x);
window.speechSynthesis.speak(msg);
}
If you go to the URL, you will see the entire sheet and the info I am trying to access. I've been trying to solve this for a few hours, and can't find any help with google.
Try this:
parsed_json['forecast']['txt_forecast']['forecastday'][0]['fcttext'];
Don't know what you expect the :0 to do, but it won't de-reference the array.

Javascript Variables Not Globally Returning / Adding Together

I'm trying to add both Facebook and Twitter share counters together, however all my efforts have failed.
<script>
tweets = 0;
function getTwitterCount(url){
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
return true;
});
}
var urlBase='http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: function(data) {
showCount(data);
}
});
var fbshares = 0;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
}
var TotalShares = tweets + fbshares;
$('#total-share-count').html(TotalShares);
</script>
I could really do with some outside insight as I've been working crazy to get this website up and running ASAP and I'm probably overlooking the most obvious of things...
Console Log Reads:
Uncaught ReferenceError: fbshares is not defined
sdk.js:64 Invalid App Id: Must be a number or numeric string representing the application id.
card.html?v=2:79 Uncaught ReferenceError: I18n is not defined
sdk.js:64 FB.getLoginStatus() called before calling FB.init().
However despite this message, the Facebook and Twitter counters are working 100%, I just cannot get them to add together.
Best Regards,
Tim
Here's a solution:
var tweets;
function getTwitterCount(url) {
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data) {
tweets = data.count;
$('#twitterCount').html(tweets);
showTotal();
});
}
var urlBase = 'http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: showCount
});
var fbshares;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
showTotal();
}
function showTotal() {
if (tweets !== undefined && fbshares !== undefined)
$('#total-share-count').html(tweets + fbshares);
}
Basically showTotal attempts to sum the two values after each callback. When both values are defined, it will place the sum into the HTML.

How to pull out certain data from returned JSON string?

So I have an application in JavaScript that takes a users photo and then sends it off to a face recognition API and it returns a JSON value, Then I have that converted to a string. But I only two of the items that are returned to me are important.I want to pull out those two (uid and confidence) and set them as variables; which I'm not entirely sure how to do. Here's an example of what is returned:
{"photos":[{"url":"http://api.skybiometry.com/fc/images/get?id=bmN2X3hybD0wMTk5c29ub3I0MXE0bjN…RyMTQzJmVxPTE1ODkmY3ZxPTY5MjcxMzEyMTI3cTImZ3Z6cmZnbnpjPTIwMTMwNDE0MTgxNjI5","pid":"F#0deeecd9274c7d8357343ed57e6aaf6c_69271312127d2","width":380,"height":300,"tags":[{"tid":"TEMP_F#0deeecd9274c7d8357343ed500c20089_69271312127d2_51.05_45.67_0_1","recognizable":true,"threshold":20,"uids":[{"uid":"sam#sam","confidence":100}],"confirmed":false,"manual":false,"width":20,"height":25.33,"center":{"x":51.05,"y":45.67},"eye_left":{"x":56.32,"y":39.67},"eye_right":{"x":46.32,"y":40},"mouth_center":{"x":48.68,"y":55.67},"nose":{"x":50.79,"y":47},"yaw":0,"roll":1,"pitch":0,"attributes":{"face":{"value":"true","confidence":60}}}]}],"status":"success","usage":{"used":5,"remaining":95,"limit":100,"reset_time_text":"Sun, 14 April 2013 18:20:53 +0000","reset_time":1365963653}}
Here is the code I'm currently using right now to return the entire string:
.done(function (result) {
alert("Received response..");
var resultObject = JSON.stringify(result);
alert(resultObject);
});
Any help is greatly appreciated!
.done(function (result) {
if(result != null) {
var uids = result.photos[0].tags[0].uids[0];
var uid = uids.uid;
var confidence = uids.confidence;
} });

Categories