AWS Lambda Parse JSON(意外令牌)

时间:2016-03-20 21:54:19

标签: json amazon-web-services aws-lambda

我正在尝试使用Lambda函数来访问API并返回JSON。

API

  

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

P.S此API ID是OW提供的演示版。

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网址的人都会看到Open Weather API的结果

1 个答案:

答案 0 :(得分:3)

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