Getting Started with JSON

December 14, 2009 | By

This post will walk through JSON basic concepts.

json loiane Getting Started with JSON

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format, widely hailed as the successor to XML in the browser.

It is easy for humans to read and write.

It is easy for machines to parse and generate.

It is based on a subset of the JavaScript Programming Language.

It is lighter than XML.

JSON versus XML

Ps.: This is only from the javascript eval() point of view.

JSON XML
JSON object are type XML data is typeless
JSON types: string, number, array, boolean XML data are all string
Data is readily accessible as JSON objects XML data needs to be parsed
Retrieving value is easy Retrieving value is difficult
JSON is supported by all browsers Cross browser XML parsing can be tricky
Simple API Complex API
Supported by many Ajax toolkit Not fully supported by Ajax toolkit
Fast object de-serialization in JavaScript Slower de-serialization in Javascript
Fully automated way of de-serializing/serializing JavaScript objects Developers have to write javascript code to serialize/se-serialize to/from XML

JSON Values

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

object Getting Started with JSONAn array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

array Getting Started with JSONA value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

value Getting Started with JSON

A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

string Getting Started with JSON

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

number Getting Started with JSON

JSON Syntax

  • For objects start the object with “{“ and end it with “}”
  • For members (properties), use pairs of string : value and separate them by commas
  • For arrays put the arrays between []
  • For elements put the values directly separated by commas

Example:

<script type="text/javascript">
var myFirstJSON = { "firstName" : "Loiane",
                    "lastName"  : "Groner",
                    "age"       : 23 };

document.writeln(myFirstJSON.firstName);  // Outputs Loiane
document.writeln(myFirstJSON.lastName);   // Outputs Groner
document.writeln(myFirstJSON.age);        // Outputs 23
</script>

This object has 3 properties or name/value pairs. The firstName and lastName are strings and age is a number.

The value can be any Javascript object (and remember everything in Javascript is an object so the value can be a string, number, array, function, even other Objects).

<script type="text/javascript">
var hobbies = { "tvseries" :
			[ //array
				{"name": "Lost", "seasons":5 },
				{"name": "Heroes", "seasons":4 },
				{"name": "Fringe", "seasons":2 },
				{"name": "The Office", "seasons":5 },
				{"name": "The Big Bang Theory", "seasons":3 },
				{"name": "True Blood", "seasons":2 },
				{"name": "Battlestar Galactica", "seasons":4 },
				{"name": "Sex and the City", "seasons":6 },
				{"name": "Friends", "seasons":10 }
			]
			"games" :
				[
				"Counter Strike" ,"Sacred 2","The Sims 3","Guitar Hero"
				]

      		};

document.writeln(hobbies.tvseries[0].name); // Outputs Lost
document.writeln(hobbies.games[3]); 	   // Outputs Guitar Hero
</script>

hobbies is an object. That object has two properties or name/value pair (tvseries and games).

tvseries is an array which holds two JSON objects showing the names and seasons of 9 TV Series. Likewise games is also an array which holds four JSON objects showing the names of games I like.

Well, this is just a start. You can study JSON functions and how to convert JSON objects now. You can also study Ajax toolkits taht support JSON.

Happy coding!

Filed in: JSON | Tags: ,

Comments (13)

  1. Nice article, simple and clear.

  2. Werner

    Hi,

    I was wondering if you did not forget a komma after the first property/value TVSeries.

    Is games array also not a property on hobbies?

    So hobbies would have two name/value pairs (TVSeries and games)

    Correct me if I am wrong.

    Cheers,

    Werner

  3. virgile

    Wouldn’t it be better with a comma at the end of the line {“name”: “Battlestar Galactica”, “seasons”:4 } ?
    Likewise, i’d say that there must be a comma at the end of line 13 and that hobby is an object with two properties, tvseries ans games.

  4. Thanks for correcting me guys!

    I already changed the code and the text.

    Cheers!

  5. ok, you are speaking in favor of JSON, but please include in that comparision box a big disclaimer on top saying it is only from the javascript eval() point of view ….. if you go to the server side, for example, it is the complete other way round.. where you have a robust support of parsing XML and a jungle of mess for parsing JSON contents :)

    nice post ….

  6. Nice article. However I think you are being a little bias. My experience with JSON might help to balance some of your points. About 4 years ago the technology my company develops used JSON extensively ( Mainly because we wanted something lightweight ). However as application requirements increased it was apparent that JSON did not have the power necessary to produce the results we wanted. While XML and JSON are very similar, XML has many more standard ways to interact with the data ( client and server side ). Arguments about XML having no type is poor at best since XML Schemas, Schematron and other mechanisms provide much better ways to qualify and validate data than JSON can offer. Additional the ability to transform XML ( Both on the browser and server ) dwarf JSON. XSLT can run in most browsers an provides a much more sophisticated and powerful approach than JSON-T does. JSON also has security vulnerabilities as @Felipe Gaúcho mentioned as well little/no support server side.

    So now, 4 years after we started our web application, and after alot of research and development there is almost no JSON left to be found. For our needs JSON just didn’t cut it and we haven’t noticed any performance issues from switching to JSON to XML ( Especially since all modern browsers use compression. Compressed XML is very close in size to compressed JSON ).

    That being said, JSON is a fine technology for many applications, and if all you need is a simple browser based data exchange mechanism JSON might be a great fit.

    Cheers,

    Casey

  7. DP

    Great article …. was very useful

  8. Intresting post. Thanks!

  9. Ricardo Cabanelas

    Well, all that stuff about JSON vs XML is just a point of view. Despite the reasons i do think that fast development is best achieved with json. It´s just too many languages and procedures to cope with, don´t you agree !

  10. ambaye

    it was interesting as my first guide of JSON