JSON (JavaScript Object Notation) is a lightweight syntax for storing and exchanging text information.
In this lesson you can learn how to create simple and multidimensional arrays and objects in JavaScript using JSON format.
Although the JSON syntax contains a minimum set of rules for structuring data in text format, JSON can represent complex data structure that can contain arrays and objects into a string that can be interchanged and used between different programming languages.

JSON Syntax

The data in JSON format are stored using name:value pairs, separated by comma. The "name" can be a string between quotes, or a number, if it is not specified, the "name" will be a numerical index, like in numeric arrays.

          - JSON can represent these data types: strings, numbers, boolean, null, array and objects.
          - Arrays are created by adding the list of values (separated by comma) between square brackets "[]".
          - Objects are created by adding "name": "value" pairs, separated by comma, between curly brackets "{}".
          - The "name", and "value" which are text string must be added between simple or double quotes (generally are used double quotes), with ":" between "name" and "value".

• Because JSON syntax is a subset of JavaScript syntax, the elements of the arrays and objects created using JSON format can be accessed, and edited directly with JavaScript functions.

JSON Array

An ordered list of values, separated by comma, between square brackets, [].
<script type="text/javascript">
// Numeric array in javascript syntax
var arr1 = new Array();
  arr1[0] = 'val 1';
  arr1[1] = 2;
  arr1[2] = 'val 3';

// the same array, created with JSON:
var jsnar = ['val 1', 2, 'val 3'];

// the elements stored in "jsnar" can be accessed like any array element
alert(jsnar[0]);        // val 1

// modify the value of the second element in "jsnar"
jsnar[1] = 7.8;
alert(jsnar[1]);         // 7.8
</script>
- Notice the second element, 2. The numeric values are not added between quotes.
The value is changend by assigning directly a new value.

JSON Object

Multiple "name":value pairs, separated by comma, between curly brackets, {}.
<script type="text/javascript">
// Object with JavaScript syntax
var siteData = new Object();
  siteData.url = 'http://coursesweb.net/';
  siteData.title = 'Web Development Courses';
  siteData.users = 1500;

// the same object, in JSON format
var jsnob = {"url": 'http://coursesweb.net/', "title": 'Web Development Courses', "users": 1500};

// accessing the "title" element in "jsnob"
alert(jsnob.title);          // Web Development Courses

// Or:
alert(jsnob['title']);       // Web Development Courses

// adding another entry in "jsnob"
jsnob.new_item = 'new entry';

alert(jsnob['new_item']);       // new entry  (the same with: alert(jsnob.new_item) )
</script>

Multidimensional array

Example with an array containing three arrays. The structures that contain the array (added between [] ), are separated by comma, all added within a main "[]".
<script type="text/javascript">
// Multidimensional arrays in JSON format
var arr2 = [
 ['php', 'html', 'javascript', 78],
 ['free courses', 'tutorials'],
 ['www.marplo.net', 'coursesweb.net', 'www.w3schools.com', 2012]
];

// accessing the first element in the second array
alert(arr2[1][0]);        // free courses

// modify the value of the first entry in the second array, in "arr2"
arr2[1][0] = 'json tutorial';
</script>
- In the example above, the "arr2" is an array containing three json arrays. Each array is a record of different values.

Multidimensional object

Example with an object containing three objects. The structures that contain the object (added between {} ), are separated by comma, all added within a main "{}".
<script type="text/javascript">
// Multidimensional object in JSON format
var jsnobj = {
 "site": {"url": 'http://coursesweb.net/', "title": 'Web Development Courses', "users": 1500},
 "page": {"course": 'javascript-jquery', "lessons": 35},
 "names": {"name_1": 'Marius', "name_2": 'Victor', "name_3": 'Alex'}
}

// accessing the 'course' item in the object "page"
alert(jsnobj.page.course);        // javascript-jquery

// Or:
alert(jsnobj['page']['course']);        // javascript-jquery

// modify the value of the "name_1", in the object in "names"
jsnobj.names.name_1 = 'MarPlo';
</script>

JSON with array and objects

1. An array containing two JSON objects. The objects are separated by comma, added within a main "[]" structure.
<script type="text/javascript">
// array with 2 objects
var arrob = [
 {"url": 'http://coursesweb.net/', "title": 'Web Development Courses', "users": 1500},
 {"url": 'http://www.marplo.net/', "title": 'Free Courses, Games, Anime', "users": 4500}
]

// accessing "users" intem of the second element in "arrob"
alert(arrob[1].users);          // 4500

// Or:
alert(arrob[1]['users']);       // 4500
</script>

2. An object containing two arrays and an object.
<script type="text/javascript">
// JSON object with 2 arrays and an object
var obj2 = {
 "courses": ['html', 'css', 'ajax'],
 "tutorials": ['jquery', 'actionscript'],
 "site": {"url": 'http://coursesweb.net/', "title": 'Web Development Courses', "users": 1500}
}

// accessing the first element in "tutorials"
alert(obj2.tutorials[0]);          // jquery

// Or:
alert(obj2['tutorials'][0]);      // jquery
</script>
- In this example, the names "courses", and "tutorials" contain array; the "site" contains an object.

Combining JSON syntax and JavaScript functions

A very useful feature of the JSON syntax is that it can be combined with JavaScript functions. Using this feature, you can create scripts with less code, and more compact data.
- In the following example it is created a JSON object with a property and a method. The property ("values") contains an array in JSON format, the method ( getVal() ) represents a JavaScript function with a parameter.
<script type="text/javascript">
// JSON object with one property (values), and a method, getVal()
var objsn = {
  "values": [2, 7, 8],
  "getVal": function(nr) {
    // multiply the value of the 3rd element in the "values" array by number in parameter
    var reval = this.values[2] * nr;
    return reval;       // returns the result
  }
};

var test = objsn.getVal(9);      // calls the getVal() method
alert(test);           // check the result (72)
</script>
- The "this" word used in the getVal() function represents the object in which the function is used. So, the "this.values[2]" returns the third value added in the "values" property of the current object ( objsn ).

• In the next lesson you can learn how to convert strings with data in JSON format, to be used in JavaScript; and, how to convert JavaScript objects into a JSON string that can be transfered to other aplications.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
JSON syntax in JavaScript

Last accessed pages

  1. Pagination Class - Script to paginate content (1435)
  2. Butterfly Kyodai (25093)
  3. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (54435)
  4. MD5 hash string in JavaScript (805)
  5. Register and show online users and visitors (16824)

Popular pages this month

  1. Bubbles3 (3397)
  2. Butterfly Kyodai (3013)
  3. Zuma Deluxe (2212)
  4. Qwop (1433)
  5. Backgammon (1307)