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!
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
stringify() to return JSON data): We will now use http. createServer() and JSON. stringify() to return JSON data from our server.
JSON can be either an array or an object.
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); }
var objToJson = { }; objToJson.response = response; response.write(JSON.stringify(objToJson));
If you alert(JSON.stringify(objToJson))
you will get {"response":"value"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With