Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  33] [ 1]  / answers: 1 / hits: 61941  / 11 Years ago, fri, october 18, 2013, 12:00:00

I'm trying to create function that can parse JSON from a url. Here's what I have so far:



function get_json(url) {
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});

res.on('end', function() {
var response = JSON.parse(body);
return response;
});
});
}

var mydata = get_json(...)


When I call this function I get errors. How can I return parsed JSON from this function?


More From » node.js

 Answers
7

Your return response; won't be of any use. You can pass a function as an argument to get_json, and have it receive the result. Then in place of return response;, invoke the function. So if the parameter is named callback, you'd do callback(response);.



// ----receive function----v
function get_json(url, callback) {
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});

res.on('end', function() {
var response = JSON.parse(body);
// call function ----v
callback(response);
});
});
}

// -----------the url---v ------------the callback---v
var mydata = get_json(http://webapp.armadealo.com/home.json, function (resp) {
console.log(resp);
});


Passing functions around as callbacks is essential to understand when using NodeJS.


[#74910] Wednesday, October 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinleyi

Total Points: 121
Total Questions: 100
Total Answers: 109

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;