从URL解析JSON数据

tur*_*tle 3 javascript node.js

我正在尝试创建可以从URL解析JSON的函数.这是我到目前为止所拥有的:

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(...)
Run Code Online (Sandbox Code Playgroud)

当我调用此函数时,我会收到错误.如何从此函数返回已解析的JSON?

use*_*012 9

return response;没有任何用处.您可以将函数作为参数传递给get_json它,并让它接收结果.然后代替return response;,调用函数.因此,如果参数已命名callback,那么您可以这样做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);
});
Run Code Online (Sandbox Code Playgroud)

将函数作为回调传递对于理解何时使用NodeJS至关重要.


Mau*_*rez 8

如果有人正在寻找不涉及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 ;
    }
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它

var gjson ;
gjson = getJSON('./first.geojson') ;
Run Code Online (Sandbox Code Playgroud)


hex*_*ide 5

HTTP 调用是异步的,因此您必须使用回调来获取结果值。一个return异步函数调用将只是停止执行。

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
});
Run Code Online (Sandbox Code Playgroud)

在这个例子中,function(json) {}作为 传递给get_json()函数fn(),当数据准备好时,fn()被调用,允许你获取 JSON。