node.js 从 URL 解析 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19440589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON data from a URL
提问by turtle
I'm trying to create function that can parse JSON from a url. Here's what I have so far:
我正在尝试创建可以从 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(...)
When I call this function I get errors. How can I return parsed JSON from this function?
当我调用此函数时,出现错误。如何从此函数返回解析的 JSON?
回答by Mauricio Gracia Gutierrez
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') ;
回答by user2736012
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);.
你的return response;不会有任何用处。您可以将函数作为参数传递给get_json,并让它接收结果。然后代替return response;,调用函数。所以如果参数是 named 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);
});
Passing functions around as callbacks is essential to understand when using NodeJS.
在使用 NodeJS 时,将函数作为回调传递是必不可少的。
回答by hexacyanide
The HTTP call is asynchronous, so you must use a callback in order to fetch a resultant value. A returncall in an asynchronous function will just stop execution.
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
});
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.
在这个例子中,function(json) {}作为 传递给get_json()函数fn(),当数据准备好时,fn()被调用,允许你获取 JSON。

