JSON 以“\”返回 (Lambda)

JSON returning with "\" (Lambda)

我正在使用 AWS Lambda 从开放天气 api 和 return 中获取 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);
        });
    });
}

它有效并且 return 是 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}"

这正在停止我的过度服务,使用(SwiftJSON)将其检测为有效 JSON。

谁能告诉我如何使 API 信息的格式正确 JSON?

我试过 .replace 像这样:

 res.on('end', function() {

        result = body.replace('\', '');
        context.succeed(result);
    });

它没有改变任何东西。仍然有相同的输出。

您可以使用:

    res.on('end', function() {
 context.succeed(body.replace(/\/g, '') );

要用什么替换 \..

您将其作为字符串发布。

尝试context.succeed(JSON.parse(结果))

来自文档

提供的结果必须JSON.stringify兼容。如果 AWS Lambda 无法进行字符串化或遇到其他错误,则会引发未处理的异常,并且 X-Amz-Function-Error 响应 header 设置为未处理。

http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html

所以本质上它是将你的 json 字符串作为一个字符串并调用 JSON.stringify ......从而转义你所看到的所有引号。通过解析的JSONobject就成功了应该不会有这个问题

在 Java 的情况下,只需 return 一个 JSONObject。看起来当 returning 字符串时,它正在尝试进行一些转换并最终转义所有引号。

对结果执行此操作:response.json()

如果使用 Java,响应可以是用户定义的对象,如下所示

class Handler implements RequestHandler<SQSEvent, CustomObject> {
    public CustomObject handleRequest(SQSEvent event, Context context) {
        return new CustomObject();
    }
}

可以找到示例代码 here