Micael
Micael

Reputation: 6970

Should JSON data contain formatted data?

When using JSON to populate a section of a page I often encounter that data needs special formatting - formatting that need to match that already on the page, which is done serverside.

A number might need to be formatted as a currency, a special date format or wrapped in for negative values.

But where should this formatting take place - doing it clientside will mean that I need to replicate all the formatting that takes place on the serverside. Doing it serverside and placing the formatted values in the JSON object means a less generic and reusable data set.

What is the recommended approach here?

Upvotes: 0

Views: 89

Answers (2)

Murph
Murph

Reputation: 10190

The generic answer is to format data as late/as close to the user as is possible (or perhaps "practical" is a better term).

Irritatingly this means that its an "it depends" answer - and you've more or less already identified the compromise you're going to have to make i.e. do you remove flexibility/portability by formatting server side or do you potentially introduct duplication by doing it client side.

Personally I would tend towards client side unless there's a very good reason not to do so - simply because we're back to trying to format stuff as close to the user as possible, though I would be a bit concerned about making sure that I'm applying the right formatting rules in the browser.

Upvotes: 2

Bjoern
Bjoern

Reputation: 16304

JSON supports the following basic types:

  • Numbers,
  • Strings,
  • Boolean,
  • Arrays,
  • Objects
  • and Null (empty).

A currency is usually nothing else than a number, but formatted according to country-specific rules. And dates are not (yet) included in JSON at all.

Whatever is recommendable depends on what you do in your application and what kind of JScript libraries you are already using. If you are already formatting alot of data in your server side code, then add it there. If not, and you already have some classes included, which can cope with formatting (JQuery and MooTools have some capabilities), do it in the browser.

So either format them in the client or format them before sending them over - both solutions work.

If you want to delve deeper into this, i recommend this wikipedia article about JSON.

Upvotes: 1

Related Questions