8

AWS Lambda を使用して、open weather 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);
        });
    });
}

それは機能し、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}"

これは、これを有効な JSON として検出する (SwiftJSON) を使用して、オーバー サービスを停止しています。

API 情報を正しくフォーマットされた JSON として出力する方法を誰か教えてもらえますか?

.replace私は次のように試しました:

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

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

何も変わりませんでした。それでも同じ出力がありました。

4

5 に答える 5

17

文字列として投稿しています。

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 オブジェクトを渡して成功させると、この問題は発生しません。

于 2016-03-21T01:35:37.653 に答える
-2

以下を使用できます。

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

\ を何も置き換えない..

于 2016-03-21T01:25:39.747 に答える