1. Computing

Structure of a JSON Document

By

JSON (JavaScript Object Notation) is a data serialization format for communicating between applications. It's a text format that features a lightweight syntax and closely mirrors the common data structures in modern programming languages such as Ruby's Arrays and Hashes. JSON can be used in a variety of places, but its most common use is to be consumed from a web API.

The format of a JSON document is quite simple. There are only two organizational structures: an ordered list (which will be mapped to a Ruby Array) and a key/value list (mapped to a Ruby Hash). The syntax is also simple, using only the brace characters { and }, bracket characters [ and ], delimiters , and : and the double-quote character ".

In addition to these two data structures, JSON provides a small amount of data types.

  • Strings - A quotes string in double quotes.
  • Numbers - An unquoted positive or negative number, with scientific notation supported.
  • Boolean values - The unquoted strings true and false.
  • Null value - The unquoted string null, the equivalent of nil in Ruby.

Below is an example JSON document describing the employees of a company. The top-level structure of the document is a Hash in brackets { and }. There are a few key/value pairs describing the top positions, and key/value pairs with Arrays as the values describing the employees in various departments.


{
  "CEO": "William Hummel",
  "CFO": "Carlos Work",
  
  "Human Resources": [
    "Inez Rockwell",
    "Kay Mcginn",
    "Larry Conn",
    "Bessie Wolfe"
  ],

  "Research and Development": [
    "Norman Reece",
    "Betty Prosser",
    "Jeffrey Barclay"
  ]
}

The top-level element of the document is a Hash. It has two key/value pairs, one for the CEO and one for the CFO. The values for both of these keys are simple strings. The next two key/value pairs hold Arrays. The keys are strings as before, but the values are Arrays of strings enclosed in brackets [ and ].

While this was a simple example, that just goes to show how simple JSON really is. There isn't much to JSON, unlike XML where all manner of meta-information can exist in attributes and such. Also, unlike XML, JSON sticks to Arrays and Hashes for its document structure, whereas XML is much more free-form. While this may sound like a disadvantage at first, it quickly becomes apparent that JSON covers just about every use case for XML while keeping things simple.

©2014 About.com. All rights reserved.