111

I'm a newb to back-end code and I'm trying to create a function that will respond to me a JSON string. I currently have this from an example

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

This basically just prints the string "random numbers that should come in the form of JSON". What I want this to do is respond with a JSON string of whatever numbers. Do I need to put a different content-type? should this function pass that value to another one say on the client side?

Thanks for your help!

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
climboid
  • 6,932
  • 14
  • 44
  • 71

7 Answers7

173

Using res.json with 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"
  });
}

Alternatively:

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);
}
Kevin Reilly
  • 6,096
  • 2
  • 25
  • 18
79
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

If you alert(JSON.stringify(objToJson)) you will get {"response":"value"}

falsarella
  • 12,217
  • 9
  • 69
  • 115
druveen
  • 1,611
  • 3
  • 15
  • 32
  • Beware that res.write(JSON.stringify()) still wait for you to "end" the response. (res.end()) ; express .json() to this for you – 131 Jun 04 '15 at 09:55
25

You have to use the JSON.stringify() function included with the V8 engine that node uses.

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

Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json in RFC4627. It is also is listed in the Internet Media Type list here.

Community
  • 1
  • 1
tyronegcarter
  • 301
  • 3
  • 7
  • Should the content-type header also be set to application/json or something like that? What is best practice for this? – ampersand May 05 '11 at 05:23
  • 1
    Yes, to make it a valid response the client will understand. Add: res.writeHead(200, {'Content-Type': 'application/json'}) before – Ali Dec 17 '12 at 13:50
13

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

res.json({"foo": "bar"});
Community
  • 1
  • 1
Greg
  • 8,574
  • 21
  • 67
  • 109
3

in express there may be application-scoped JSON formatters.

after looking at express\lib\response.js, I'm using this 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);
}
Sam Vloeberghs
  • 1,082
  • 5
  • 18
  • 29
Amir Arad
  • 6,724
  • 9
  • 42
  • 49
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);

I have used the above code in my existing project.

Soura Ghosh
  • 879
  • 1
  • 9
  • 16
-2

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

response.write(JSON.stringify({ x: 5, y: 6 }));

know more

MD SHAYON
  • 7,001
  • 45
  • 38