AWS Lambda Parse JSON(意外令牌)

AWS Lambda Parse JSON (Unexpected token)

我正在尝试获取 Lambda 函数来访问 API 和 return JSON。

API

http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a

P.S这个APIID是OW提供的demo。

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 和 return 它,所以任何查看我的 API url 的人都会看到 Open 的结果天气 API

您正在将 URL 传递给 JSON.parse(),而不是 JSON 字符串。首先,您需要使用 http.get() 之类的方法从 URL 获取 JSON 数据。也许查看这个类似问题的答案:Parsing JSON data from a URL