Home > JavaScript > JSON Data Wrappers

JSON Data Wrappers

Many people use JSON nowadays to output information. Its lightweight and awesome! So why not. But I find that people neglect to maintain an appropriate syntax, if you will, while writing JSON output.

Now, what I mean by “wrappers” is that most examples I’ve seen send back a JSON list. This list should always be wrapped with additional server information in case of internal server errors (500 errors) or the need for other clarifications (errors, total item counts, etc).

A basic example wrapper

{
"status": "ok",
"message": "",
"resultCount": 10,
"resultOffset": 3
"resultSet" : ["one", "two", "three"]
}

Using this Style of wrapper I know:

  • There were no problems on the server side (the status entry)
  • There are 10 results in total for whatever I want (the resultCount entry)
  • The results are offset by 3 (the resultOffset)
  • I have 3 results to display to the end user (the resultSet entry)

Note that some of these parameters could be optional (like offset).  But make sure that whoever is writing the JavaScript knows this!  It could otherwise cause unrecoverable JavaScript errors.

Server Error handled gracefully

{
"status": "error",
"message": "Database Error",
"resultCount": 0,
"resultSet" : []
}

Here’s an example of a server 500 that, despite being completely unrecoverable, still gracefully displays JSON as to not cause execution errors in the browser.  Note that I omitted resultOffset as I am using this parameter optionally.  I do return an empty resutSet though.  JUST in case someone forgot to program any error handling in the JavaScript.

Looking Forward

This is only a simple example of what your wrapper should include, feel free to add other information like a timestamp for when it was served or other important data.  To get you started look at some examples from Google or Yahoo for ideas.

blog comments powered by Disqus