การตอบสนองด้วยออบเจ็กต์ JSON ใน Node.js (การแปลงอ็อบเจ็กต์ / อาร์เรย์เป็นสตริง JSON)


101

ฉันเป็นคนใหม่ของโค้ดแบ็กเอนด์และฉันกำลังพยายามสร้างฟังก์ชันที่จะตอบสนองต่อสตริง 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

คำตอบ:


165

การใช้res.jsonกับ Express:

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);
}

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

ถ้าalert(JSON.stringify(objToJson))คุณจะได้รับ{"response":"value"}


ระวังว่า res.write (JSON.stringify ()) ยังคงรอให้คุณ "สิ้นสุด" การตอบกลับ (ส่งซ้ำ()) ; ด่วน. json () ให้คุณ
131

23

คุณต้องใช้JSON.stringify()ฟังก์ชันที่มาพร้อมกับเครื่องยนต์ V8 ที่โหนดใช้

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

แก้ไข:เท่าที่ผมรู้ว่าIANAได้จดทะเบียนอย่างเป็นทางการชนิด MIME สำหรับ JSON เป็นapplication/jsonในRFC4627 นอกจากนี้ยังมีชื่ออยู่ในอินเทอร์เน็ตประเภทสื่อรายการที่นี่


ควรตั้งค่าส่วนหัวประเภทเนื้อหาเป็น application / json หรือไม่? แนวทางปฏิบัติที่ดีที่สุดสำหรับสิ่งนี้คืออะไร?
เครื่องหมายและ

1
ใช่เพื่อให้เป็นการตอบสนองที่ถูกต้องลูกค้าจะเข้าใจ เพิ่ม: res.writeHead (200, {'Content-Type': 'application / json'}) ก่อน
Ali

13

ต่อJamieL 's คำตอบที่จะโพสต์อื่น :

เนื่องจาก Express.js 3x อ็อบเจ็กต์ตอบกลับมีเมธอด json () ซึ่งตั้งค่าส่วนหัวทั้งหมดให้คุณ

ตัวอย่าง:

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

ฉันจะทำเช่นเดียวกันกับไฟล์ JSON ได้อย่างไร
HGB

อย่าลืม res.end () ถ้าคุณใช้สิ่งนี้ฉันต้องการ
Charles Harring

3

ใน Express อาจมีรูปแบบ 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);
}

นี่คือการส่งกลับฟังก์ชันจาวาสคริปต์หรือไม่ ฉันเข้าใจถูกไหม แล้วจะทำไปทำไม แค่อยากรู้อยากเห็น
Sam Vloeberghs

1
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.