Whilst building a new reporting engine this week I was advised by a friend to consider using JSON as a simple and effective way to store the business rules. Having not used JSON before, I decided to take a quick look and found it to be a very straightforward yet elegant way of storing data.
What is JSON?
JSON (JavaScript Object Notation) is a neat and structured text-based data format that is an accepted alternative to XML.
JSON comprises of two structures:
- A set of name/values pairs, which is basically an object. Both the name and value mus be in double quotes.
- An ordered list of values, which is basically an array. Values in turn can store strings, numbers, objects, arrays, Booleans and nulls.
Basic Objects
var jString = { "Firstname": "Joe", "Lastname": "Bloggs" }
document.writeln(jString.Firstname); // Output Joe
document.writeln(jString.Firstname); // Output Joe
Basic Array
var jString = { "Firstname": "Joe", "Lastname": "Bloggs", "Sports": ["Football", "Tennis", "Jujitsu"] }
for (var i in jString.Sports) {
document.writeln(jString.Sports[i]);
}
// Ouput: Football Tennis Jujitsu
for (var i in jString.Sports) {
document.writeln(jString.Sports[i]);
}
// Ouput: Football Tennis Jujitsu