Jam*_*esG 5 json http-get amazon-web-services aws-lambda openweathermap
我正在使用AWS Lambda从开放天气api获取JSON并将其返回.
这是我的代码:
var http = require('http');
exports.handler = function(event, context) {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
Run Code Online (Sandbox Code Playgroud)
它工作并返回JSON,但它在每个之前添加反斜杠"如此:
"{\"coord\":{\"lon\":145.77,\"lat\":-16.92},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04d\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":303.15,\"pressure\":1008,\"humidity\":74,\"temp_min\":303.15,\"temp_max\":303.15},\"wind\":{\"speed\":3.1,\"deg\":320},\"clouds\":{\"all\":75},\"dt\":1458518400,\"sys\":{\"type\":1,\"id\":8166,\"message\":0.0025,\"country\":\"AU\",\"sunrise\":1458505258,\"sunset\":1458548812},\"id\":2172797,\"name\":\"Cairns\",\"cod\":200}"
Run Code Online (Sandbox Code Playgroud)
这是使用(SwiftJSON)将此检测为有效JSON来停止我的过度服务.
任何人都可以告诉我如何使API信息以正确格式化的JSON出现?
我试过.replace这样:
res.on('end', function() {
result = body.replace('\\', '');
context.succeed(result);
});
Run Code Online (Sandbox Code Playgroud)
它没有改变任何东西.仍然有相同的输出.
Jef*_*eff 11
您将其作为字符串发布.
尝试context.succeed(JSON.parse(result))
来自文档
提供的结果必须与JSON.stringify兼容.如果AWS Lambda无法进行字符串化或遇到其他错误,则会抛出未处理的异常,并将X-Amz-Function-Error响应标头设置为Unhandled.
http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
所以基本上它将你的json字符串作为一个字符串并在其上调用JSON.stringify ...因此,当你看到时,转义所有的引号.传递解析的JSON对象成功,它不应该有这个问题
| 归档时间: |
|
| 查看次数: |
4646 次 |
| 最近记录: |