Information Technology @ PaynesNotebook.net




JSON

External Resources:

Introduction

Examples

1. Simple JavaScript Object Example

JSON is directly related to JavaScript object. Here are some examples. Note double quotes are optional for name.

HTMLFirst Name: <span id="harryFirstName"></span><br />
Last Name: <span id="harryLastName"></span><br />
Age: <span id="harryAge"></span>

Hermione's Name: <span id="hermioneName"></span><br />
Hermione's age: <span id="hermioneAge"></span>
JavaScript // Note " is optional for name.
var harryPotter = {
  "firstName": "Harry",
  lastName: "Potter",
  "age": 11 };

document.getElementById("harryFirstName").innerHTML = harryPotter.firstName;
document.getElementById("harryLastName").innerHTML = harryPotter.lastName;
document.getElementById("harryAge").innerHTML = harryPotter.age;

// Hermione
var hermioneObj = new Object();
hermioneObj.name = "Hermione Granger";
hermioneObj.age = 11.1;

document.getElementById("hermioneName").innerHTML = hermioneObj.name;
document.getElementById("hermioneAge").innerHTML = hermioneObj.age;
Result First Name:
Last Name:
Age:

Hermione's Name:
Hermione's age:

2. JSON Examples

HTML <span id="albusFirstName"></span> <span id="albusLastName"></span><br />
<span id="cedricFirstName"></span> <span id="cedricLastName"></span>
JSON Object // Dumbledore
var txt1 = '{"firstName" : "Albus", "lastName" : "Dumbledore"}';

// Evaluate and execute txt1.
var albusObj = eval("(" + txt1 + ")");

// Update elements.
document.getElementById("albusFirstName").innerHTML = albusObj.firstName; document.getElementById("albusLastName").innerHTML = albusObj.lastName;
JSON Array // Characters
var txt2 = '{"characters": ['
  + '{"firstName":"Harry", "lastName":"Potter"},'
  + '{"firstName":"Hermione", "lastName":"Granger"},'
  + '{"firstName":"Ron", "lastName":"Weasley"},'
  + '{"firstName":"Cedric", "lastName":"Diggory"} ]}';

// Use JSON.parse() instead of eval().
// var charObj = eval("(" + txt2 + ")");

var charObj = JSON.parse(txt2);

// Update elements.
document.getElementById("cedricFirstName").innerHTML = charObj.characters[3].firstName;
document.getElementById("cedricLastName").innerHTML = charObj.characters[3].lastName;
Result