Node.jsのJSONオブジェクトでの応答(オブジェクト/配列をJSON文字列に変換)


98

私はバックエンドコードの初心者であり、JSON文字列に応答する関数を作成しようとしています。私は現在例からこれを持っています

function random(response) {
  console.log("Request handler 'random was called.");
  response.writeHead(200, {"Content-Type": "text/html"});

  response.write("random numbers that should come in the form of json");
  response.end();
}

これは基本的に、文字列「JSON形式の乱数」を出力するだけです。私がこれにしたいことは、どんな数字のJSON文字列でも応答することです。別のコンテンツタイプを配置する必要がありますか?この関数はその値をクライアント側の別の人に渡す必要がありますか?

ご協力いただきありがとうございます!


res.json({"キー": "値"});
Amol M Kulkarni 2015年

回答:


160

Expressでres.jsonを使用する:

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

または:

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}

76
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

もしあればalert(JSON.stringify(objToJson))あなたが得ます{"response":"value"}


res.write(JSON.stringify())は、応答が「終了」するまで待機することに注意してください。(res.end()); あなたのためにこれまで)(.json表現
131

22

JSON.stringify()ノードが使用するV8エンジンに含まれている関数を使用する必要があります。

var objToJson = { ... };
response.write(JSON.stringify(objToJson));

編集:私の知る限り、IANAはJSONのMIMEタイプを次のように正式に登録しています。application/json RFC4627のに。また、こちらのインターネットメディアタイプリストにもリストされています


content-typeヘッダーもapplication / jsonなどに設定する必要がありますか?このためのベストプラクティスは何ですか?
アンパサンド、

1
はい、それを有効な応答にするためにクライアントは理解します。追加:res.writeHead(200、{'Content-Type': 'application / json'})before
Ali

12

パーJamieLさんの答え別のポスト

Express.js 3x以降、応答オブジェクトにはjson()メソッドがあり、すべてのヘッダーが正しく設定されます。

例:

res.json({"foo": "bar"});

JSONファイルでどうすれば同じことができますか?
HGB

これを使用する場合、res.end()を忘れないでください。これが必要でした
Charles Harring

2

明確に言うと、アプリケーションスコープのJSONフォーマッタが存在する場合があります。

express \ lib \ response.jsを確認した後、次のルーチンを使用しています。

function writeJsonPToRes(app, req, res, obj) {
    var replacer = app.get('json replacer');
    var spaces = app.get('json spaces');
    res.set('Content-Type', 'application/json');
    var partOfResponse = JSON.stringify(obj, replacer, spaces)
        .replace(/\u2028/g, '\\u2028')
        .replace(/\u2029/g, '\\u2029');
    var callback = req.query[app.get('jsonp callback name')];
    if (callback) {
        if (Array.isArray(callback)) callback = callback[0];
        res.set('Content-Type', 'text/javascript');
        var cb = callback.replace(/[^\[\]\w$.]/g, '');
        partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
    }
    res.write(partOfResponse);
}

これはJavaScript関数を送り返すためのものですか?私はこれを正しくしていますか?そして、なぜあなたはそれをしますか?好奇心旺盛
Sam Vloeberghs、2014

0
const http = require('http');
const url = require('url');

http.createServer((req,res)=>{

    const parseObj =  url.parse(req.url,true);
    const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]

    if(parseObj.pathname == '/user-details' && req.method == "GET") {
        let Id = parseObj.query.id;
        let user_details = {};
        users.forEach((data,index)=>{
            if(data.id == Id){
                user_details = data;
            }
        })
        res.writeHead(200,{'x-auth-token':'Auth Token'})
        res.write(JSON.stringify(user_details)) // Json to String Convert
        res.end();
    }
}).listen(8000);

上記のコードを既存のプロジェクトで使用しました。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.