Parsing JSON data from a URL

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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?

回答1:

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.



回答2:

In case someone is looking for an solution that does not involve callbaks

    function getJSON(url) {         var resp ;         var xmlHttp ;          resp  = '' ;         xmlHttp = new XMLHttpRequest();          if(xmlHttp != null)         {             xmlHttp.open( "GET", url, false );             xmlHttp.send( null );             resp = xmlHttp.responseText;         }          return resp ;     } 

Then you can use it like this

var gjson ; gjson = getJSON('./first.geojson') ; 


回答3:

The HTTP call is asynchronous, so you must use a callback in order to fetch a resultant value. A return call in an asynchronous function will just stop execution.

function get_json(url, fn) {   http.get(url, function(res) {     var body = '';     res.on('data', function(chunk) {       body += chunk;     });      res.on('end', function() {       var response = JSON.parse(body);       fn(response);     });   }); };  get_json(url, function(json) {   // the JSON data is here }); 

In this example, function(json) {} is passed into the get_json() function as fn(), and when the data is ready, fn() is called, allowing you to fetch the JSON.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!