prototype js parsing multiple json objects - javascript

I am a prototype newbie and am unclear on how to process multiple json objects returned. For example I would like to return a simple JSONObject map indicating the success/failure and also return a JSONArray that I can index and build an select:options from. Now each json object will be upt in the header with a different name. How do I parse that out client-side and alert on a failure name/value else build the select:option element? tia.

Suppose your /someurl service sends a reply like this:
{
"status": "ok",
"data":["apples", "oranges", "bananas"]
}
What I have done here is to combine the two objects into a single object. In the client you can handle it something like this.
new Ajax.Request('/someurl', {
method:'get',
requestHeaders: {Accept: 'application/json'},
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
if(json.status != 'ok')
{
alert('status "'+json.status+'" not ok')
return; // or throw a fit
}
json.data.each(function(elt){
alert(elt); // or display it, whatever
});
}
});

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

Node.js and Express - Sending JSON object from SoundCloud API to the front-end makes it a string

I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.
var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
tracks.on('data', function (chunk) {
console.log(typeof(chunk)); // where I determine that I receive an object
res.send(chunk);
});
//console.log(tracks.data);
}).on("error", function(e){
console.log("Got error: "+e);
});
But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())
$('#search').click(function(e){
e.preventDefault();
var q = $("#query").val();
$.ajax({
url: '/search',
type: 'POST',
data: {
"query": q
},
success: function(data){
alert(typeof(data));
alert(data);
},
error: function(xhr, textStatus, err){
alert(err);
}
})
});
I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)
JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.
var obj = JSON.parse(data);
Another example would be:
var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22

ngResource retrive unique ID from POST response after $save()

So I have a Resource defined as follows:
angular.module('questionService', ['ngResource'])
.factory('QuestionService', function($http, $resource) {
var QuestionService = $resource('/api/questions/:key', {}, {
query: {
method:'GET',
isArray:true,
},
save: {
method: 'POST',
}
});
return QuestionService
});
And later on I take some form input and do the following
var newQ = {
txt: $scope.addTxt
};
QuestionService.save(newQ)
The server responds to the POST request both by reissuing the JSON for the object and setting the location header with the new unique ID. The problem is that Angular is not saving that returned JSON or the location header into the object and it is not getting set with the ID from the server for future operations. I've tried a number of things such as:
transformResponse: function(data, headersGetter) {
locationHeader = headersGetter().location;
key = locationHeader.split('/').slice(-1)[0];
data.key = key;
return data;
}
However the returned data item doesn't seem to be getting used. Am I missing something? This seems like a pretty common use case for interacting with a REST api.
Thanks!
You need to have a success handler to assign the new id to newQ manually:
QuestionService.save(newQ, function(data) {
newQ.id = data.id;
});
But there is a better to achieve the same. Because your QuestionService is a resource class object, you can instantiate your newQ like this:
var newQ = new QuestionService({text: $scope.addTxt});
Then, call $save() of newQ:
newQ.$save();
Now newQ should have the new id returned by the server.
I have Asp.Net server with WebApi2 running, i use Ok(number) to return content, and it return for example '6' as result. once it return, the angular show an object containing promise and state, and prototypes and a deep repeated hierarchy, but no value, no '6'.
So i went to see where the data goes, for seeing where the data is i define a transform, and i see awo the data, but it's not a json...
later i change it to following, and now i have a obj in my success function, which has sub property called 'returnValue' (as i defined), and this object hold my value.
transformResponse: function(data, header){
var obj={};
obj.returnValue=angular.fromJson(data);
return obj;
},

Javascript Object returns junk values

I'm trying to assign values to a javascript object and when doing so, some junk values end up in there which seem like array methods like 'push', 'pop','splice' etc. The following is my code.
function myTest(){
var userArray = new Object();
var req = new Request.JSON({
url: '/myTest.php',
method: 'post',
noCache: true,
data: 'userID=999',
onSuccess: function(json){
for(var key in json){
userArray = json[key];
for (var row in userArray){
alert(row) // This returns values like '$family','push','pop', 'reverse' etc.
}
}
},
onException: function(xhr){
alert("Unable to process your request");
},
onFailure: function(xhr){
alert("Unable to connect to the server");
}
}).send();
}
I am not sure what I'm missing here but it looks like I certainly am. Any help on this would be greatly appreciated.
Never use for...in on an array. Period. The garbage values you are seeing are properties of the array prototype.
See this related question.
for (var row in userArray){
if(userArray.hasOwnProperty(row))
alert(row) ;
}
Details here. Basically, for loop will take all available properties/functions. And you must check if it belongs to that object only or is inherited.

NodeJS and Backbone's fetch

This is my front-end code (using fetch)
var MyModel = Backbone.Model.extend();
var MyCollection = Backbone.Collection.extend({
url: '/questions',
model: MyModel
});
var coll = new MyCollection();
coll.fetch({
error: function (collection, response) {
console.log('error', response);
},
success: function (collection, response) {
console.log('success', response);
}
});
and this is my back-end code (using app.get)
app.get('/questions', function (request, response) {
console.log('Inside /questions');
response.writeHead(200, {
'Content-Type': 'text/json'
});
response.write('{test:1}');
response.end();
});
The problem is that although the response is as expected, the client-side error callback is called. When I remove the line response.write('{test:1}');, the success callback is called. Any ideas as to what I might be doing wrong?
Well {test:1} is not valid JSON.
{ "test":"1" }
OR
{ "test":1 }
is however, try one of those instead.
Keys are strings in JSON, and strings in JSON must be wrapped in double quotes check out JSON.org for more information.
To ensure you have valid JSON for more complex objects just use JSON.stringify():
var obj = { test : 1 };
response.write(JSON.stringify(obj)); //returns "{"test":1}"
Also, the correct Content-Type for json is application/json
{test:1} isn't valid JSON, you should try { "test":"1" }.
Another solution is to check Express's render.json function to see how it does sending json to the browser:
https://github.com/visionmedia/express/blob/master/lib/response.js#L152-172
If you're using express you need to res.send will automatically convert objects into JSON. If you're worried about it, there's a new one called res.json that will convert anything into JSON.
var obj = {super: "man"}
res.send(obj) // converts to json
res.json(obj) // also converts to json
You don't need need writeHead(), write(), or end().
http://expressjs.com/guide.html

Categories

Resources