AJAX - Extracting Info from JSON Object - javascript

I have data in a JSON object with the following format:
[{"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}]
I've started to write some code to pull information from an API, but am not sure how to extract information (for instance, "stringforfeature3" if I somehow call "Feature 3") from the JSON object.
ajax: {
type: "GET",
url: '/api/apiname/info/moreinfo', //where i'm pulling info from
dataType: "JSON",
success: function(data, textStatus, jqXHR) {
return {
title: // Where I'd like to use the extracted information
};
}
},
Any advice would be greatly appreciated!

First of all, the response is an array, You need to get the first element like this
response = data[0];
Do you know each of the keys in advance? If yes,
{ title: response['Feature 3'] }
Else you can loop over response
for (var key in response) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + response[key]);
}
}

You should be able to extract the data using square bracket notation:
success: function(data, textStatus, jqXHR) {
return {
title: data[0]['Feature 3']
};
}
You result is an array, so I used data[0] to get the first item of array, or {"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}.
In JavaScript you can access the same variable either using object.variable or object['variable']. Since your variable name has spaces, you are left with second option - data[0]['Feature 3']. Your result will be stringforfeature3.

Related

formatting json data from api

I'm using api to extract exchange rates in json form right now the result shows like this
"RUB":1,"AED":0.06317,"AFN":1.5074,"ALL":2.0112,"AMD":7.0904,"ANG":0.03079,"AOA":6.9821,"ARS":2.4694,"AUD":0.02624,"AWG":0.03079,"AZN":0.02896,"BAM":0.03457,"BBD":0.0344,"BDT":1.7593,"BGN":0.03457,"BHD":0.006468,"BIF":33.7214,"BMD":0.0172,"BND":0.02457,"BOB":0.1177,"BRL":0.08918,"BSD":0.0172,"BTN":1.3948,"BWP":0.2247,"BYN":0.04456,"BZD":0.0344,"CAD":0.02333,"CDF":33.5622,"CHF":0.01691,"CLP":16.1531,"CNY":0.1225,"COP":74.4278,"CRC":10.7597,"CUP":0.4128,"CVE":1.949,"CZK":0.4341,"DJF":3.0571,"DKK":0.1319,"DOP":0.9116,"DZD":2.3957,"EGP":0.3326,"ERN":0.258,"ETB":0.8631,"EUR":0.01768,"FJD":0.03885,"FKP":0.01562,"FOK":0.1319,"GBP":0.01562,"GEL":0.04833,"GGP":0.01562,"GHS":0.1788,"GIP":0.01562,"GMD":0.9243,"GNF":141.1552,"GTQ":0.133,"GYD":3.4174,"HKD":0.1353,"HNL":0.421,"HRK":0.1332,"HTG":1.9453,"HUF":7.1365,"IDR":259.0919,"ILS":0.05999,"IMP":0.01562,"INR":1.3949,"IQD":23.8415,"IRR":717.8181,"ISK":2.4479,"JEP":0.01562,"JMD":2.5882,"JOD":0.0122,"JPY":2.4632,"KES":2.0638,"KGS":1.3947,"KHR":67.2399,"KID":0.02624,"KMF":8.6956,"KRW":24.3376,"KWD":0.005154,"KYD":0.01433,"KZT":8.2208,"LAK":273.8169,"LBP":25.9315,"LKR":6.1903,"LRD":2.6162,"LSL":0.3071,"LYD":0.08099,"MAD":0.1845,"MDL":0.331,"MGA":68.8987,"MKD":1.0155,"MMK":35.7873,"MNT":53.4153,"MOP":0.1394,"MRU":0.6182,"MUR":0.7619,"MVR":0.2625,"MWK":17.5369,"MXN":0.3462,"MYR":0.07854,"MZN":1.0862,"NAD":0.3071,"NGN":7.3194,"NIO":0.6133,"NOK":0.1814,"NPR":2.2317,"NZD":0.02979,"OMR":0.006614,"PAB":0.0172,"PEN":0.06603,"PGK":0.05993,"PHP":1.0023,"PKR":4.0715,"PLN":0.08333,"PYG":118.1834,"QAR":0.06261,"RON":0.08681,"RSD":2.0444,"RWF":18.1732,"SAR":0.06451,"SBD":0.138,"SCR":0.2232,"SDG":9.3095,"SEK":0.1934,"SGD":0.02458,"SHP":0.01562,"SLE":0.2519,"SLL":251.8519,"SOS":9.2863,"SRD":0.4595,"SSP":10.8377,"STN":0.433,"SYP":42.7533,"SZL":0.3071,"THB":0.645,"TJS":0.1733,"TMT":0.05898,"TND":0.05427,"TOP":0.04078,"TRY":0.3166,"TTD":0.1157,"TVD":0.02624,"TWD":0.5443,"TZS":39.6052,"UAH":0.6335,"UGX":64.9736,"USD":0.0172,"UYU":0.6988,"UZS":187.3274,"VES":0.1434,"VND":407.0389,"VUV":2.0628,"WST":0.04733,"XAF":11.5942,"XCD":0.04644,"XDR":0.01352,"XOF":11.5942,"XPF":2.1092,"YER":4.2578,"ZAR":0.3072,"ZMW":0.2673,"ZWL":10.0256
I would like to format and make it look using javascript as data is getting fetched by javascript
function currencyexchange(currency1){
console.log(currency1);
$.ajax({
url: "php/currency.php",
type: 'POST',
dataType: 'json',
data: {
code:currency1
},
//if user enters correct data and api gives back the data then we run success funtion
success: function(result) {
console.log(JSON.stringify(result),null,4);
//if status of data is ok we fetch the data from fields and put them in results table in html
if (result.status.name == "ok") {
//fetching fields from api and showing them in html table
$('#exchangedata').html(JSON.stringify(result['data']).replace(/['"]+/g, '').slice(1,-1));
}else{
//if the upper condition fails
console.log("error");
}
},
//if there is no success in retrieving data from api
error: function(jqXHR, textStatus, errorThrown) {
console.log("error");
$('#txterror').html("Enter Valid Id");
}
});
Something like:
// add { and } to the json string (if it's not already there)
const data = `{ "RUB":1,"AED":0.06317,"AFN":1.5074,"ALL":2.0112,"AMD":7.0904,"ANG":0.03079,"AOA":6.9821,"ARS":2.4694,"AUD":0.02624,"AWG":0.03079,"AZN":0.02896,"BAM":0.03457,"BBD":0.0344,"BDT":1.7593,"BGN":0.03457,"BHD":0.006468,"BIF":33.7214,"BMD":0.0172,"BND":0.02457,"BOB":0.1177,"BRL":0.08918,"BSD":0.0172,"BTN":1.3948,"BWP":0.2247,"BYN":0.04456,"BZD":0.0344,"CAD":0.02333,"CDF":33.5622,"CHF":0.01691,"CLP":16.1531,"CNY":0.1225,"COP":74.4278,"CRC":10.7597,"CUP":0.4128,"CVE":1.949,"CZK":0.4341,"DJF":3.0571,"DKK":0.1319,"DOP":0.9116,"DZD":2.3957,"EGP":0.3326,"ERN":0.258,"ETB":0.8631,"EUR":0.01768,"FJD":0.03885,"FKP":0.01562,"FOK":0.1319,"GBP":0.01562,"GEL":0.04833,"GGP":0.01562,"GHS":0.1788,"GIP":0.01562,"GMD":0.9243,"GNF":141.1552,"GTQ":0.133,"GYD":3.4174,"HKD":0.1353,"HNL":0.421,"HRK":0.1332,"HTG":1.9453,"HUF":7.1365,"IDR":259.0919,"ILS":0.05999,"IMP":0.01562,"INR":1.3949,"IQD":23.8415,"IRR":717.8181,"ISK":2.4479,"JEP":0.01562,"JMD":2.5882,"JOD":0.0122,"JPY":2.4632,"KES":2.0638,"KGS":1.3947,"KHR":67.2399,"KID":0.02624,"KMF":8.6956,"KRW":24.3376,"KWD":0.005154,"KYD":0.01433,"KZT":8.2208,"LAK":273.8169,"LBP":25.9315,"LKR":6.1903,"LRD":2.6162,"LSL":0.3071,"LYD":0.08099,"MAD":0.1845,"MDL":0.331,"MGA":68.8987,"MKD":1.0155,"MMK":35.7873,"MNT":53.4153,"MOP":0.1394,"MRU":0.6182,"MUR":0.7619,"MVR":0.2625,"MWK":17.5369,"MXN":0.3462,"MYR":0.07854,"MZN":1.0862,"NAD":0.3071,"NGN":7.3194,"NIO":0.6133,"NOK":0.1814,"NPR":2.2317,"NZD":0.02979,"OMR":0.006614,"PAB":0.0172,"PEN":0.06603,"PGK":0.05993,"PHP":1.0023,"PKR":4.0715,"PLN":0.08333,"PYG":118.1834,"QAR":0.06261,"RON":0.08681,"RSD":2.0444,"RWF":18.1732,"SAR":0.06451,"SBD":0.138,"SCR":0.2232,"SDG":9.3095,"SEK":0.1934,"SGD":0.02458,"SHP":0.01562,"SLE":0.2519,"SLL":251.8519,"SOS":9.2863,"SRD":0.4595,"SSP":10.8377,"STN":0.433,"SYP":42.7533,"SZL":0.3071,"THB":0.645,"TJS":0.1733,"TMT":0.05898,"TND":0.05427,"TOP":0.04078,"TRY":0.3166,"TTD":0.1157,"TVD":0.02624,"TWD":0.5443,"TZS":39.6052,"UAH":0.6335,"UGX":64.9736,"USD":0.0172,"UYU":0.6988,"UZS":187.3274,"VES":0.1434,"VND":407.0389,"VUV":2.0628,"WST":0.04733,"XAF":11.5942,"XCD":0.04644,"XDR":0.01352,"XOF":11.5942,"XPF":2.1092,"YER":4.2578,"ZAR":0.3072,"ZMW":0.2673,"ZWL":10.0256}`;
// parse the JSON and for each entry of the parsed object create html
Object.entries(JSON.parse(data)).forEach( ([k, rate]) =>
document.body.insertAdjacentHTML(`beforeend`, `<div>${k}: ${rate}</div>`) );
Just Map over the Object Entries & put a <br/> after every key value pair. Or, using the same method, you can just create a new element for each item.
const result = {
data: {
RUB: 1,
AED: 0.06317,
AFN: 1.5074,
ALL: 2.0112,
AMD: 7.0904,
ANG: 0.03079,
AOA: 6.9821,
ARS: 2.4694,
AUD: 0.02624,
AWG: 0.03079,
AZN: 0.02896,
BAM: 0.03457,
BBD: 0.0344,
BDT: 1.7593,
BGN: 0.03457,
BHD: 0.006468,
BIF: 33.7214
}
};
document.body.innerHTML = Object.entries(result["data"])
.map(([k, v]) => `${k}: ${v}<br/>`)
.join("");
I got it formatted perfectly in different lines using the following code.
$('#exchangedata').html(JSON.stringify(result['data'],null, 4).replace(/['"]+/g, '').slice(1,-1).split(",").join("<br /><hr/>")
The .replace() regex helped to remove all the double quotes inside the json data
and .slice() helped with removing the curly braces from first and last index of data.
and split()and join () helped to remove the "," and place a line break after every currency

Iterating over a list of skus in jQuery to dynamically add it to HTML

I'm at a beginner level in front-end development; I'm attempting to refactor some code as a side project for myself to improve my skills. My job has a list of images targeted by their skus being dynamically added to div's. I have included the following code that I have attempted to refactor.
var getProductNavigateDetail = function(skuList) {
var postUrl = "/Browse/ProductDynamicComponent/GetProductNavigateDetailJson";
$.ajax({
url: postUrl,
type: "POST",
data: { skus: skuList },
dataType: "json",
success: function(result) {
if (result[0] != null) {
$('#a1Price').html(result[0].FormattedPrice);
$('#a1Name').html(result[0].Name);
$('#a1Link').attr('href', result[0].NavigateUrl);
$('#a1Link').attr('href', result[1].NavigateUrl);
$('#b1Price').html(result[1].FormattedPrice);
$('#b1Name').html(result[1].Name);
$('#c1Price').html(result[2].FormattedPrice);
$('#c1Name').html(result[2].Name);
$('#c1Link').attr('href', result[2].NavigateUrl);
$('#a2Price').html(result[14].FormattedPrice);
$('#a2Name').html(result[14].Name);
$('#a2Link').attr('href', result[14].NavigateUrl);
$('#b2Price').html(result[15].FormattedPrice);
$('#b2Name').html(result[15].Name);
$('#b2Link').attr('href', result[15].NavigateUrl);
$('#c2Price').html(result[16].FormattedPrice);
$('#c2Name').html(result[16].Name);
$('#c2Link').attr('href', result[16].NavigateUrl);
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
getProductNavigateDetail('160555,665087,159816,482743,228984,519217,320165,216235,229010,687943,332256,513663,482508,216243,330495,340218,668637,232524,414899,444139,560632,329734');
It seems pretty obvious that it just needs to iterated over with a loop so I made this code.
var getProductNavigateDetail = function(skuList) {
var postUrl = "/Browse/ProductDynamicComponent/GetProductNavigateDetailJson",
imageURL = "www.website.com/";
$.ajax({
url: postUrl,
type: "POST",
data: { skus: skuList },
dataType: "json",
success: function(result) {
if (result[0] != null) {
for (let i = 0; i < skuList.length; i++) {
$('#a' + [i] + 'Price').html(result[i].FormattedPrice);
$('#a' + [i] + 'Name').html(result[i].Name);
$('#a' + [i] + 'Link').attr('href', result[i].NavigateUrl);
$('#a' + [i] + 'Image').attr('src', imageURL + result[i].ImagePath);
}
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
getProductNavigateDetail('160555,665087,159816,482743,228984,519217');
Trying to figure out a way to get the implementation of the first but just using a short iteration with jQuery. Any tips, advice or scenarios to look at would be gladly appreciated!
Ok so result is the response from the AJAX request, and I'm assuming this is an array of products. such as:
[ { FormattedPrice: 'somethin', Name: 'someName' } ]
What you send as data is a comma-seperated list of SKUs ('160555,665087,159816,482743,228984,519217'). Firstly, you assume that the result you get back is in the exact same order as your comma-seperated list you sent in, and that it will always contain the same number of products as you have asked for. If any products are missing from the database, and your array is 1 less than you expect, you will get an error in your loop as your try and access that missing array entry...
Secondly, your loop is not going to implement the exact same thing as what is done in the original code (the div ID's can start with either a, b or c, and then it jumps from results[2] to results[14]). So I am unsure how you are going to target the correct div ID with only the index of the array you are looping through unless it follows a strict pattern.
So overall I'm not entirely sure what you need to achieve and it would be hard to write the code for you without seeing the full result object and your front-end HTML.

How to parse JSON with multiple rows/results

I don't know if this is malformed JSON string or not, but I cannot work out how to parse each result to get the data out.
This is the data.d response from my $.ajax function (it calls a WebMethod in Code Behind (C#)):
{"Row":[
{"ID1":"TBU9THLCZS","Project":"1","ID2":"Y5468ASV73","URL":"http://blah1.com","Wave":"w1","StartDate":"18/06/2015 5:46:41 AM","EndDate":"18/06/2015 5:47:24 AM","Status":"1","Check":"0"},
{"ID1":"TBU9THLCZS","Project":"2","ID2":"T7J6SHZCH","URL":"http://blah2.com","Wave":"w1","StartDate":"23/06/2015 4:35:22 AM","EndDate":"","Status":"","Check":""}
]}
With all the examples I have looked at, only one or two showed something where my 'Row' is, and the solutions were not related, such as one person had a comma after the last array.
I would be happy with some pointers if not even the straight out answer.
I have tried various combinations of response.Row, response[0], using $.each, but I just can't get it.
EDIT, this is my ajax call:
$.ajax({
url: "Mgr.aspx/ShowActivity",
type: "POST",
data: JSON.stringify({
"ID": "null"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblResErr').html('<span style="color:red;">' + thrownError);
}
});
At the moment I have just been trying to get ID1 value and ID2 value into the console.
EDIT (Resolved): Thanks to YTAM and Panagiotis !
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
data = JSON.parse(data);
console.log(data);
}
Now the console is showing me an array of two objects, and now I know what to do with them !!
First you have to parse the string with JSON.parse
var data= JSON.parse(rowData);
Then you will get object like given below,
data = {
"Row": [
{
"ID1":"TBU9THLCZS",
"Project":"1",
"ID2":"Y5468ASV73",
"URL":"http://blah1.com",
"Wave":"w1",
"StartDate":"18/06/2015 5:46:41 AM",
"EndDate":"18/06/2015 5:47:24 AM",
"Status":"1",
"Check":"0"
},
{
"ID1":"TBU9THLCZS",
"Project":"2",
"ID2":"T7J6SHZCH",
"URL":"http://blah2.com",
"Wave":"w1",
"StartDate":"23/06/2015 4:35:22 AM",
"EndDate":"",
"Status":"",
"Check":""
}
]}
Here I am giving two options either direct retrieve data from data variable or through loop.
data.row[0].ID1
data.row[0].Project
data.row[0].ID2
and so on
OR
use loop,
var result = json.row;
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
}
}
Hope this helps.
you may be getting a json string from the web method rather than an actual JavaScript object. Parse it into a JavaScript object by
doing
var data = JSON.parse(response);
then you'll be able to iterate over data.Row

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

Javascript: Trouble parsing json response

Spring is returning a json-encoded object with four properties. One of which is a property named "array". I want the contents of this array.
Here's the whole json response:
ee
{"map":null,"array":[{"id":2,"description":"Cloud For Dev","businessSize":2,"businessType":9,"businessLocation":3},{"id":3,"description":"Cloud For Prod","businessSize":2,"businessType":9,"businessLocation":3}],"string":null,"bool":false}
0
I'm not actually sure what the "ee" or 0 mean... Anyway, I'm trying to parse it like this:
$.ajax({
type: "GET",
url: "/ajax/rest/teamService/list",
dataType: "json",
success: function (response) {
var teamArray = response.array;
var $el = $("#teamSelect");
$el.empty();
$.each(teamArray[0], function(team) {
alert(team.description);
$el.append($("<option></option>").attr("value", team.id).text(team.description));
});
// Reattach the plugin
$("#teamSelect").selectbox("detach");
$("#teamSelect").selectbox("attach");
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus === 'error') {
setTimeout(function() { window.location = '/do/login'; }, 7000);
}
}
});
And I'm getting the alert box pop up 6 times (should be 2), and each time it says "undefined" rather than the actual description.
The select box itself has four empty options.
Seems like I'm iterating over the json encoded object's four parameters, NOT the two contents of the enclosed array.
How can I fix this?
Try this - teamArray[0] should be only teamArray
$.each(teamArray, function(i,team) {
alert(team.description);
$el.append($("<option></option>").attr("value", team.id).text(team.description));
});
Right now, you're looping over the keys of teamArray[0], hence the six alerts. Loop over teamArray. Also, $.each's callback takes indexInArray, valueOfElement. May as well not jQuery through that:
for(var i = 0; i < teamArray.length; i++) {
var team = teamArray[i];
...
}

Categories

Resources