Costa Michailidis
Costa Michailidis

Reputation: 8178

Are JSON APIs supposed to return strings or JavaScript Objects?

Let's say I ask Mailchimp for subscriber data, and they send back an http request with JSON in the body. Should I be able to go:

var thingy = body.property;

Or should I have to go:

var object = JSON.parse(body);
var thingy = object.property;

?

Also, does the node.js body parse parse JSON for me?

Upvotes: 1

Views: 1739

Answers (2)

jfriend00
jfriend00

Reputation: 707836

JSON is sent over the wire from the server as a string. That's what JSON is - a string format.

Whether or not it arrives at your code as a string or as already parsed Javascript object depends entirely upon the code you are using to make the http request and perhaps what headers the server sets and what auto-detection the code doing the Ajax call makes.

If the response header sets the type to json, then some code making the request will automatically parse it for you into Javscript. Other code will leave that to the caller to do. If the server does not set the proper headers, then some code will auto-detect it as JSON and parse it and other code will not.

So ... bottom line. It depends entirely upon what the server is doing in its response and what code is being use to make the request. You can very easily just do a console.log(body) and see whether you have a JSON string or an already parsed Javascript object.

If you really weren't sure what behavior you would get, you can test the type and act accordingly (though a given server and calling code should be consistent so you shouldn't have to vary your behavior) once you test how it behaves.

if (typeof body === "string") {
    body = JSON.parse(body);
}

Upvotes: 3

taxicala
taxicala

Reputation: 21769

Depends on the API, usually you get the response header Content-type: application/json. If that is the case there's probably no need to parse the response as most of the clients will understand that it's a json object and parse it for you. Anyhow, not all clients will do this automatically.

Upvotes: 2

Related Questions