Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responding with a JSON object in Node.js (converting object/array to JSON string)

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!

like image 542
climboid Avatar asked May 05 '11 04:05

climboid


People also ask

How convert JSON object to string in node JS?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How do I return a JSON object in node JS?

stringify() to return JSON data): We will now use http. createServer() and JSON. stringify() to return JSON data from our server.

Can JSON response be an array?

JSON can be either an array or an object.


2 Answers

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); } 
like image 198
Kevin Reilly Avatar answered Oct 17 '22 06:10

Kevin Reilly


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

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

like image 30
druveen Avatar answered Oct 17 '22 06:10

druveen