user3846091
user3846091

Reputation: 1703

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 }"

Upvotes: 1

Views: 267

Answers (3)

salezica
salezica

Reputation: 77089

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)

Upvotes: 1

Callebe
Callebe

Reputation: 1097

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

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

Upvotes: 1

elzi
elzi

Reputation: 5692

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

Upvotes: 0

Related Questions