Risposta con un oggetto JSON in Node.js (conversione di oggetto / matrice in stringa JSON)


98

Sono un principiante del codice back-end e sto cercando di creare una funzione che mi risponda con una stringa JSON. Al momento ho questo da un esempio

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

Questo fondamentalmente stampa solo la stringa "numeri casuali che dovrebbero presentarsi sotto forma di JSON". Quello che voglio che questo faccia è rispondere con una stringa JSON di qualsiasi numero. Devo inserire un tipo di contenuto diverso? questa funzione dovrebbe passare quel valore a un altro da parte del client?

Grazie per l'aiuto!


res.json ({"Key": "Value"});
Amol M Kulkarni

Risposte:


161

Utilizzo di res.json con 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"
  });
}

In alternativa:

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

Se alert(JSON.stringify(objToJson))otterrai{"response":"value"}


Fai attenzione che res.write (JSON.stringify ()) aspetta ancora che tu "termini" la risposta. (res.end ()); esprimi .json () a questo per te
131

22

Devi usare la JSON.stringify()funzione inclusa con il motore V8 che utilizza il nodo.

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

Modifica: per quanto ne so, IANA ha registrato ufficialmente un tipo MIME per JSON come application/jsonin RFC4627 . E 'inoltre è elencata nella Internet Media Type lista qui .


Anche l'intestazione del tipo di contenuto dovrebbe essere impostata su application / json o qualcosa del genere? Qual è la migliore pratica per questo?
commerciale

1
Sì, per renderlo una risposta valida il cliente capirà. Aggiungi: res.writeHead (200, {'Content-Type': 'application / json'}) prima di
Ali

12

Per JamieL 's risposta a un altro post :

Poiché Express.js 3x, l'oggetto risposta ha un metodo json () che imposta correttamente tutte le intestazioni.

Esempio:

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

Come posso fare lo stesso con un file JSON?
HGB

non dimenticare res.end () se usi questo, ne avevo bisogno
Charles Harring

2

in express ci possono essere formattatori JSON con ambito applicazione.

dopo aver esaminato express \ lib \ response.js, sto usando questa routine:

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

Serve per restituire le funzioni javascript? Sto capendo bene? E perché dovresti farlo? Solo curioso
Sam Vloeberghs

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

Ho usato il codice sopra nel mio progetto esistente.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.