Saturday, February 26, 2011

Working with JSON and AS3: Part 1

Today we will learn about JavaScript Object Notation (JSON) and why should we use it with AS3.

JSON is a lightweight text-based data exchanging standart designed to be easy readable for humans. It came from the Java Script programming language and represents simple associative arrays. Even though it has Javascript in its name, it is very widely used in all programming languages, mainly to transfer data between a server and a web application.

JSON serves as an alternative to XML. Take a look at this small staff data base in XML:

<staff>

<person>
<firstName>John</firstName>
<lastName>Parker</lastName>
<age>32</age>
<country>Canada</country>
<job>Programmer</job>
</person>

<person>
<firstName>Peter</firstName>
<lastName>Anderson</lastName>
<age>30</age>
<country>USA</country>
<job>System administrator</job>
</person>

<person>
<firstName>Bob</firstName>
<lastName>Johnson</lastName>
<age>35</age>
<country>Canada</country>
<job>Coder</job>
</person>

</staff>

It weighs 465 bytes.

Now, take a look at the JSON text file, with the same data in it:

{
"staff":
[
 {
 "firstName":"John",
 "lastName":"Parker",
 "age":"32",
 "country":"Canada",
 "job":"Programmer"
 },

 {
 "firstName":"Peter",
 "lastName":"Anderson",
 "age":"30",
 "country":"USA",
 "job":"System administrator"
 },

 {
 "firstName":"Bob",
 "lastName":"Johnson",
 "age":"35",
 "country":"Canada",
 "job":"Coder"
 }
]
}

It weighs 354 bytes. That is around 25% less than the XML file (it is like that just in this example - it might be even more in other situations!). Now imagine that we have to send 1000 staff members instead of 3 - the JSON will take significally less space on disc and will take less time to load in the application.

As you can see, the JSON file is simply an Object. We can create properties and associative arrays in it.

I've written the data to be easy to read for humans, but that is absolutely not necessary. These hashes are almost never written by humans, but generated by programs. They are sent in one line (no line breaks, no unnecessary whitespaces) and might take even less space than in our example.

To parse JSON using AS3, I will use some classes from the library written by the good Adobe people called as3corelib. But we'll do that next time!

Thanks for reading!

Related:

Working with JSON and AS3: Part 2
Working with JSON and AS3: Part 3

No comments:

Post a Comment