Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Get Started With JSON

JSON is a format for describing data that is easily converted to most programming languages. Many APIs, such as Flickr and Twitter, now offer their results in this format.

The acronym JSON (pronounced like the name “Jason”) stands for JavaScript Object Notation. It’s a way of annotating data that’s relatively easy for humans to read and write. This helps explain its recent popularity. As Ajax applications, which depend heavily on JavaScript, have become common, programmers have searched for an easy way to transfer data. Converting JSON to something usable in JavaScript takes one line of code and automatically works in all browsers.


Contents

  1. A Simple Example: A List of Movies
    1. Creating the JavaScript Object
    2. Accessing the JavaScript Object
  2. Objects with More Attributes: A Movie Review
    1. Creating and Accessing the JavaScript Object
  3. Combination Example: One Movie and its Many Reviews
    1. Creating and Accessing the JavaScript Object
  4. Using JSON with Your Favorite Language
  5. APIs that Return JSON

A Simple Example: A List of Movies

Let’s say we wanted to store the first five Friday the 13th movies (Jason? Get it?) for later access. In most programming languages, an array would be appropriate. Arrays hold an ordered collection of similar data.

JSON includes a way to describe arrays. So, the JSON text might look like this:

{"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}

The squiggly brackets surround the entire object. Whereas an array holds a list in a certain order, an object is an unordered collection. Objects hold attributes that point to values. A value could be one number or a single line of text. Or, a value can be an array, like it is here.

Our object has one attribute, named “movielist.” Attributes are in quotes, because they are a string (a fancy programming term for text) that holds the name of the attribute. After the quotes comes a colon, which separates the attribute from the value.

The square brackets contain an array, which holds our ordered list of other values. This will make more sense when we see it in action.


Creating the JavaScript Object

Written directly into JavaScript, our JSON text looks a little different:

var movielisttext = "{"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}";

First, we are making a new variable to hold the text. That variable is named movielisttext. Since it’s a JavaScript string, the whole JSON text is surrounded by quotes. Next, any quotes inside the JSON have to be “escaped” with a backslash in front. Otherwise, JavaScript gets confused about which quotes we want for display and which quotes are part of the programming.

Now that we have a JavaScript variable holding our JSON text, we need to convert it to a JSON object. I promised we’d be able to do this with one line of code. Here it is:

var jsonobj = eval("(" + movielisttext + ")");

The special JavaScript function we use to convert JSON text into an object is called eval, short for evaluate. It can take text that could be JavaScript and make it into actual JavaScript. To create an object from JSON text, all we have to do is pass the string to eval after surrounding the text with parentheses.


Accessing the JavaScript Object

Finally, you can grab the array value from the object by using its attribute name, movielist:

var moviearray = jsonobj["movielist"];



You can then access the array like you would any JavaScript array. For example, here is the first Friday the 13th movie:

var firstmovie = moviearray[0];

Remember that arrays start counting at zero, not one. That’s why there’s a zero inside the brackets. The first movie is the zeroth element of the array.

You can also access individual movies directly in the object, without pulling the array out. Here’s how you would grab the third movie from the object:

var thirdmovie = jsonobj["movielist"][2];


Objects with More Attributes: A Movie Review

Arrays are only a small example of the data JSON can hold. What if we wanted to have a bunch of information held together in one object? All we have to do it give it more attributes.

Let’s write some JSON to hold some information normally contained in a basic movie review. We want to know the name of the reviewer, how he or she rates the movie, and some prose describing the reviewer’s thoughts.

Here’s how that might look in JSON:

{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"}

This looks similar to our first example, but now we have several attributes, and they are separated by commas. Arrays also use commas to separate values. The difference here is that an object names each value with an attribute name.

Note: there are no quotes around the number of stars. When including numbers, JSON does not require quotes. In fact, if you want the number to let you add other numbers to it, for example, it cannot be in quotes.


Creating and Accessing the JavaScript Object

Just like in the first example, creating a JavaScript object from JSON text is easy. First, declare the text:

var reviewtext = "{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"}";

Then evaluate the text as an object:

var jsonobj = eval("(" + reviewtext + ")");

We can access the object attributes in the same way we retrieved the movie array in the first example. Here is how we get the reviewer’s name:

var reviewername = jsonobj["reviewer"];

JavaScript objects also have a quicker way to get at attributes. This method doesn’t require brackets and quotes:

var reviewername = jsonobj.reviewer;

var numberstars = jsonobj.stars;

var reviewerthoughts = jsonobj.text;

Just place a period after the object and then type in the name of the attribute. If you want to use the shorter method, it’s best to stick to attribute names that have no spaces.


Combination Example: One Movie and its Many Reviews

So far, the JSON examples have been fairly simple. For this final example, we will combine the first two examples to show how objects can be nested inside of other objects or arrays.

We want to use JSON text to hold basic information about a movie, then also contain a list of its reviews. Here’s how it might look:

{"title": "Friday the 13th", "year": 1980, "reviews": [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"}, {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}

The object that we create will have three attributes: title (a string), year (a number), and reviews (an array). This last attribute will contain a list of other values. In our very first example, our array contained strings. Here, the array contains other objects — review objects, like the one we created in the previous example.


Creating and Accessing the JavaScript Object

To access the information in the JSON text, we need one line to declare the text and the other to evaluate it:

var moviereviewtext = "{"title": "Friday the 13th", "year": 1980, "reviews": [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"}, {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}";

var jsonobj = eval("(" + moviereviewtext + ")");

Now, to access the first review’s information, we need to dig to a second level of attributes:

var reviewername = jsonobj.reviews[0].reviewer;

var numberstars = jsonobj.reviews[0].stars;

var reviewerthoughts = jsonobj.reviews[0].text;

JSON can be nested many layers deep, making it a good choice for even complex data. Since the syntax is minimal (just a few brackets, quotes, and colons), sending data with JSON doesn’t require a lot of extra bandwidth.


Using JSON with Your Favorite Language

There is at least one implementation of JSON in most popular web programming languages.

Java, Perl, .NET, Lisp, Erlang — you’ll find many JSON implementations listed at the bottom of this page.


APIs that Return JSON

Here are a sampling of APIs that use JSON or offer the option to get data returned in JSON format:


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles