Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return null, an empty object or an empty array for json with no data?

Tags:

json

jquery

I am sending an ajax request that will search a database. If no results are found, is there a reason to choose to return null, {} or []? Is one considered "standard" or "best practice"?

like image 996
TecBrat Avatar asked Apr 10 '14 19:04

TecBrat


People also ask

Is it better to return empty array or null?

Empty collection. Always. It is considered a best practice to NEVER return null when returning a collection or enumerable.

Is empty array allowed in JSON?

Handling null and empty arrays and objects used in JSON data is described. JSON data has the concept of null and empty arrays and objects.

Should API return null or empty?

If you want to split your workflow and more explicitly capture when something is not set, use null. If you would rather the program just keep doing as it does, use an empty string. The important thing is that you are consistent, pick a common return and stick with that.

Is empty string null in JSON?

Yes, JSON has the null value (which is indeed treated as a value, not as the absence of value), and the empty string, and they are different.


1 Answers

The differences are pretty negligible.

null is the usual way to denote "no value", but your client side code will need to explicitly check for that.

If the response actually means "here are the results, but they're empty", [] or {} might be more suitable, as long as you match the format of non-empty responses (i.e. if the client is expecting an array, don't send {}, and vice versa).

Basically:

  • If an empty result set is a special case and you want to write explicit behavior for it, null seems more appropriate.
  • If your client expects an array (e.g. it will loop through the results), then use [].
  • If your client expects a map of key-value pairs (e.g. it will loop through keys or will use result[someKey]), then use {}.
  • If your client expects a single object (i.e. it expects the result to have well-known properties and will do something like result.someProperty), then null is better than returning an empty object.

Or more clearly: If the client thinks of the result as a single value, use null. If the client thinks of it as a list, use []. If the client thinks of it as a map, use {}.

like image 127
Avish Avatar answered Sep 23 '22 23:09

Avish