简体   繁体   中英

NODEJS unable to send json formatted response?

I am trying to send json response from my nodejs application to the client. However, the response does not seem to be in the right format can someone point me what is it that i am doing wrong ?

Below is subset of my code

var insertdata = "create-fail";
var updatedata = "update-fail";
var deletedata = "delete-fail";

insertdata = "{ create:pass ,";
updatedata = "update:pass ,";
deletedata = "delete:pass }";

var jsondata = insertdata+updatedata+deletedata;
res.send(JSON.stringify(jsondata));

Output browser:

"{ create:pass ,update:pass ,delete:pass }"

JSON.stringify should receive an object, not a string.

var jsondata = {'create':'pass', 'update':'pass', 'delete':'pass'};
res.send(JSON.stringify(jsondata));

This is an object:

object = { hello: 1 }

This is a string:

string = "{ 'hello': 1 }"

The string looks similar to the object, because its format is JSON (Javascript Object Notation), which is inspired in the way object is declared above.

Objects can't travel across the internet, but strings can. You can go from object to string using JSON.stringify() :

string = JSON.stringify(object)

When you receive it on the other side, go back using JSON.parse() :

object = JSON.parse(string)

jsondata is a string - and then you're stingifying it. If you're using jQuery, use $.parseJSON or use the json2 library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM