从URL解析JSON数据

从URL解析JSON数据

本文介绍了从URL解析JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(...)

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

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

推荐答案

您的返回响应; 没有任何用处。您可以将函数作为参数传递给 get_json ,并让它接收结果。然后代替返回响应; ,调用该函数。因此,如果参数名为 callback ,则需要回调(响应);

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);
});

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

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

这篇关于从URL解析JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:16