Monday, February 23, 2015

JSON Data can be modified like

var employees = [
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter","lastName""Jones"}
];


employees[0].firstName = "Gilbert";

employees[0]["firstName"] = "Gilbert";

first entry in the JavaScript object array can be accessed like

var employees = [
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter","lastName""Jones"}
];


// returns John Doeemployees[0].firstName + " " + employees[0].lastName;


// returns John Doeemployees[0]["firstName"] + " " + employees[0]["lastName"];

JSON vs XML

For AJAX applications, JSON is faster and easier than XML:
Using XML
  • Fetch an XML document
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
Using JSON
  • Fetch a JSON string
  • JSON.Parse the JSON string

JSON Object Creation in JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>JSON Object Creation in JavaScript</h2>

<p id="demo"></p>

<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'

var obj = JSON.parse(text);

document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>

</body>
</html>

JSON Object Creation in JavaScript

What is JSON

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand

XML example defines an employees object with 3 employee records

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

JSON example defines an employees object, with an array of 3 employee records

{"employees":[
    {"firstName":"John""lastName":"Doe"}, 
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]}