How to iterate through $.JSON results array with $.each - json

I am only getting back the first result in the array, and want to retrieve all the available results.
function runForm(){
$("#stock_news").html("");
var stockSymbol = $("input").val();
//very long str
var newsStocks = "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Ffinance.yahoo.com
%2Fq%3Fs%3D"+stockSymbol+"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22yfi_headlines
%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa'&format=json&diagnostics=true&callback=";
//getJSON
$.getJSON(newsStocks, function(data) {
var headlines = data.query.results.a[0];
//newsStr
newsStr = "<h3 style='text-decoration:underline'>Current Headlines</h3><p><ol>
<li><a href='"+headlines.href+"'>"+headlines.content+
"</a></li></ol></p>";
$("#stock_news").html(newsStr);
});

You haven't given enough information, but I could guess that this var headlines = data.query.results.a[0]; is your issue. It would seem like the other results are there, but you're filtering them out. console.log(data) and console.log(data.query.results) and look at what all is in there. Otherwise, update your question with more information.
Update:
This is a very basic ajax call (with jQuery) and a for loop to loop through and use each result.
$.get('path/here', function(data) {
//if your data is an array
for (var i=0; i<data.length; ++i) {
var item = data[i];
console.log(item);
}
});
Here's a live demo (click), but I'm not going to use the ajax data since the path is not valid.
Here's the same example, but using $.each. I prefer the for loop...why use jQuery for something so simple?
$.get('path/here', function(data) {
$.each(data, function(item, index) {
console.log(index);
});
});

Related

node.js: put asynchronous returns in one object or array

I am missing something fundamental in terms of callbacks/async in the code below: why do I get:
[,,'[ {JSON1} ]']
[,,'[ {JSON2} ]']
(=2 console returns) instead of only one console return with one proper table, which is want I want and would look like:
[,'[ {JSON1} ]','[ {JSON2} ]']
or ideally:
[{JSON1},{JSON2}]
See my code below, getPTdata is a function I created to retrieve some JSON via a REST API (https request). I cannot get everything at once since the API I'm talking to has a limit, hence the limit and offset parameters of my calls.
offsets = [0,1]
res = []
function goGetData(callback) {
for(var a = 0; a < offsets.length; a++){
getPTdata('stories',
'?limit=1&offset='+offsets[a]+'&date_format=millis',
function(result){
//called once getPTdata is done
res[a] = result
callback(res)
});
}
}
goGetData(function(notgoingtowork){
//called once goGetData is done
console.log(res)
})
Solved like this:
offsets = [0,1]
res = []
function goGetData(callback) {
var nb_returns = 0
for(var a = 0; a < offsets.length; a++){
getPTdata('stories','?limit=1&offset='+offsets[a]+'&date_format=millis', function(result){
//note because of "loop closure" I cannot use a here anymore
//called once getPTdata is done, therefore we know result and can store it
nb_returns++
res.push(JSON.parse(result))
if (nb_returns == offsets.length) {
callback(res)
}
});
}
}
goGetData(function(consolidated){
//called once goGetData is done
console.log(consolidated)
})

how to ensure request is done sequentially?

I'd like to request one page after another, the following code seems request all the pages in the same time, is there a way to fetch one page after the previous one is done? thanks
var Promise = require("bluebird");
var request = Promise.promisifyAll(require('request'));
var URLS = ["http://sample.com/j1", "http://sample.com/j2"]
Promise.map(URLS, function (item) {
return request.postAsync({url: item}).spread(function (response,body) {
var items = JSON.parse(body)
return items
})
}).then(function (r) {
console.log(r.length)
})
You can set the concurrency level, which is specific to bluebird.
Promise.map(URLS, function (item) {
return request.postAsync({url: item}).spread(function (response,body) {
var items = JSON.parse(body)
return items
}, { concurrency: 1})
This will issue all the promises one at a time.

Using Q to return secondary query in node with express and mysql

New to node, As I am cycling through a roster of students, I need to check and see if a teacher has requested them for tutoring.
I realized I can't just do this:
var checkRequest = function(id){
var value = '';
roster.query('SELECT * FROM teacher_request WHERE student_id ='+id, function(err, row){
value = row.length;
}
return value;
}
After a bit of digging around promises looked like a great solution, but if I simply return the deferred.promise from the checkRequest function, all I get is an object that says [deferred promise] which I can't access the actual data from. (Or have not figured out how yet)
If I follow along with their api and use .then (as illustrated in the getRow) function, I am back in the same problem I was in before.
function checkRequest(id) {
console.log(id);
var deferred = Q.defer();
connection.query('SELECT * FROM teacher_request WHERE student_id ='+id, function(err, row){
deferred.resolve(row.length);
});
return deferred.promise;
}
var getRow = function(id){
checkRequest(id).then(function(val) {
console.log(val); // works great
return val; //back to the same problem
});
}
The roster needs to be able to be pulled from an external API which is why I am not bundling the request check with the original roster query.
Thanks in advance
From the stuff you posted, I assume you have not really understood the concept of promises. They allow you to queue up callbacks, that get executed, when the asynchronous operation has finished (by succeeding or failing).
So instead of somehow getting the results back to your synchronous workflow, you should convert that workflow to work asynchronous as well. So a small example for your current problem:
// your students' ids in here
var studentsArray = [ 1, 2, 5, 6, 9 ];
for( var i=0; i<studentsArray.length; i++ ) {
checkRequest( i )
.then( function( data ){
console.log( data.student_id );
// any other code related to a specific student in here
});
}
or another option, if you need all students' data at the same time:
// your students' ids in here
var studentsArray = [ 1, 2, 5, 6, 9 ];
// collect all promises
var reqs = [];
for( var i=0; i<studentsArray.length; i++ ) {
reqs.push( checkRequest( i ) );
}
Q.all( reqs )
.then( function(){
// code in here
// use `arguments` to access data
});

Query a JSON list of dict

[{"time":136803,"price":"1.4545","amount":"0.0885","ID":"112969"},
{"time":136804,"price":"2.5448","amount":"0.0568","ID":"5468489"},
{"time":136805,"price":"1.8948","amount":"0.0478","ID":"898489"}]
I have a large JSON file like the one above. It is a list of dictionaries. I want to choose a time and find the value assoaciated with that time. I will not know where in my list the time is located only the value for the time. Is there a way I can say, for time 136804, make x = to price? Or should I loop through each value? I also want to use this value (x) in a mathematical function.
My fist idea is to use brute force by going through each item and checking it for a matching time value in a loop.
Is this the best way?
Take a look at SpahQL http://danski.github.io/spahql/ which we use to query JSON in order to select values and subsequently change them as required.
I did something similar to this recently. JSON file I had to query had around 6000 lines and around 500 JSON objects. My query function given below loops through the each object to select the matching objects, but it can fetch any result within few milliseconds.
var data = '[{"time":136803,"price":"1.4545","amount":"0.0885","ID":"112969"},'+ '{"time":136804,"price":"2.5448","amount":"0.0568","ID":"5468489"},'+ '{"time":136805,"price":"1.8948","amount":"0.0478","ID":"898489"}]';
var data = JSON.parse(data);
var query = function(data, select, andwhere) {
var return_array = [];
$.each(data, function (i, obj) {
var temp_obj = {};
var where = true;
if (andwhere) {
$.each(andwhere, function(j, wh) {
if (obj[wh.col] !== wh.val) {
where = false;
}
});
}
if (where === false) {
return;
}
$.each(obj, function (j, elem) {
if (select.indexOf(j.trim())!==-1) {
temp_obj[j] = elem;
}
});
return_array.push(temp_obj);
});
return return_array;
};
var result = query(data, ['price','amount'],[{"col":"time","val":136804}]);
console.log(JSON.stringify(result));
http://jsfiddle.net/bejgy3sn/1/

JSON.stringify gives me wrong json array

I have this code:
var sidebars = {};
var counter = 0;
// Loop through all already crated sidebars
$('.custom_dynamic_sidebars li').each(function(event) {
sidebars[counter] = $(this).text();
counter++;
});
var sidebars_string = JSON.stringify(sidebars);
but it gives me this string:
{\"0\":\"aa\",\"1\":\"bb\"}
Here is javascript which sends array to the server:
$.ajax({
url:"/welit_2/wp-admin/admin-ajax.php",
type:'POST',
data:'action=dynamic_sidebars&sidebars='+sidebars_string+'',
success:function(results) {
console.log(results);
}
});
does anyone know what am I doing wrong?
thx for your time
So I found a solution If you run stripslashes() on the JSON string before you output it, it works fine