我正在尝试获取 Lambda 函数来访问 API 并返回 JSON。
API
http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a
P.S 此 API ID 是 OW 提供的 demo ID。
Lambda 代码
var jsonurl = "http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a";
var data = JSON.parse(jsonurl);
exports.handler = function(event, context) {
console.log(data);
context.done(null, data); // SUCCESS with message
};
错误
{
"errorMessage": "Unexpected token h",
"errorType": "SyntaxError",
"stackTrace": [
"Object.parse (native)",
"Object.<anonymous> (/var/task/index.js:3:17)",
"Module._compile (module.js:456:26)",
"Object.Module._extensions..js (module.js:474:10)",
"Module.load (module.js:356:32)",
"Function.Module._load (module.js:312:12)",
"Module.require (module.js:364:17)",
"require (module.js:380:17)"
]
}
日志输出
START RequestId: 8ca0fbd1-eee5-11e5-b9dd-31048a8d5a45 Version: $LATEST
Syntax error in module 'index': SyntaxError
at Object.parse (native)
at Object.<anonymous> (/var/task/index.js:3:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
END RequestId: 8ca0fbd1-eee5-11e5-b9dd-31048a8d5a45
REPORT RequestId: 8ca0fbd1-eee5-11e5-b9dd-31048a8d5a45 Duration: 173.76 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 9 MB
谁能看出问题所在吗?
我希望 lambda 能够获取 json 并返回它,这样任何查看我的 API url 的人都会看到来自 Open Weather API 的结果
最佳答案
您正在将 URL 传递给 JSON.parse()
,而不是 JSON 字符串。首先,您需要使用 http.get()
之类的方法从 URL 获取 JSON 数据。也许看看这个类似问题的答案:Parsing JSON data from a URL
关于json - AWS Lambda 解析 JSON(意外 token ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36120078/