JSON is written with a TEXT based JavaScript Object Notation that is used to STORE or EXCHANGE data. It is important to note that JSON is NOT an OBJECT—it is a JavaScript Object NOTATION which is simply text. However, it may be stored as an object (var myObject = JSON (JavaScript Object Notation).
Because JSON is text, it can be read and used as a data format by any programming language which makes it language independent.
IMPORTANT NOTE: There is no such thing as a JSON object. It is not an object but a STRING.,
When exchanging data between a browser and a server, the data must be text, so JSON is an ideal solution to accomplish this task:
The JSON syntax is a VERY SIMILAR to a JavaScript Object syntax, hence, its name. Data is created as name/value (or sometimes called key/value) pairs separated by a colon with each name/value pair separated by a comma and all name/value pairs within a set of curly braces:
{"name1" : value1, "name2" : value2,"name3" : value3}
The window.onload code block method is used for convenient for each example in this tutorial:
<script> window.onload = function(){
} // end of window.onload function
</script>
However, it is best practice to use either:
This will allow you to use these more than once. You could also avoid using the window.onload code block by placing the code in a script tag above the closing body tag (</body>) and reference an external JavaScript file (<script src= "externalJavaScript.js"></script>). Like CSS external file (*.css), the JSON syntax is written in an external file with an *.json extension.
<script> window.onload = function(){
} // end of window.onload function
</script>
<script> window.onload = function(){ console.log("---------- JSON Syntax ------------");
{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"}
} // end of window.onload function
</script>
You can assign JSON to a object (variable):
NOTE: Besides a JavaScript object, an array can also be used to create a JSON format.
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
console.log(myPersonalObject);
You can access data from an object by using the dot syntax (object.property_name):
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
console.log(myPersonalObject); console.log(myPersonalObject.firstName + " " + myPersonalObject.lastName);
Data in an object can be accessed by assigning the property name a new value:
console.log(myPersonalObject);
myPersonalObject.firstName = "Sheila";
console.log(myPersonalObject.firstName + " " + myPersonalObject.lastName);
Data is a JavaScript object can be converted to a JSON string using the JSON.stringify() function BEFORE it is sent to a server:
<script>
window.onload = function(){
console.log("------ SEND DATA ------");
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
var myJSON = JSON.stringify(myPersonalObject);
window.location = "my_json_data.php?x=" + myJSON; // [Add php file later]
} // end of window.onload function
</script>
CODE EXPLANATION:
If data is received in a JSON format, JavaScript can use the built-in JSON.parse() function to convert a JSON formatted string into a native JavaScript object(s).
<h1 id="myData">This phrase will be replaced with dynamic content later.</h1>
<script>
window.onload = function(){
console.log("------ RECEIVE DATA ------");
var myPersonalObject = '{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"}';
console.log("-------------- Receive Data ------------");
console.log(myPersonalObject);
var myObject = JSON.parse(myPersonalObject);
document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName;
} // end of window.onload function
</script>
EXAMPLE: Open the receive_data.html file created earlier and save it as receive_data_with_date.html, make the following highlighted changes and then preview result in browser.
EXAMPLE PAGE
<script>
window.onload = function(){
console.log("------ RECEIVE DATA WITH DATE ------");
var myPersonalObject = '{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "startDate":"12-12-12"}';
console.log(myPersonalObject);
var myObject = JSON.parse(myPersonalObject);
myObject.startDate = new Date(myObject.startDate);
document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName + "<br>" + myObject.startDate;
} // end of window.onload function
</script>
Alternatively, the optional second parameter of the JSON.parse() called reviver which is a function can be used to check each property before returning a value.
Delete the highlighted strikethrough line and and the other hightlighted lines.
<script>
window.onload = function(){
console.log("------ RECEIVE DATA WITH DATE------");
var myPersonalObject = '{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "startDate":"12-12-12"}';
console.log(myPersonalObject);
var myObject = JSON.parse(myPersonalObject, function (key, value) {myObject.startDate = new Date(myObject.startDate);
if (key == "startDate") {
return new Date(value);
} else {
return value;
}
}); // End of if statement
document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName + "<br>" + myObject.startDate;
} // end of window.onload function
</script>
When storing and retrieving data locally, the text format is a common format to use.
<script>
window.onload = function(){
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
var myJSON = JSON.stringify(myPersonalObject);
// Store data TO Local Storage
localStorage.setItem("storeJSON", myJSON);
// Retrieving data FROM Local Storage
text = localStorage.getItem("storeJSON");
myObject = JSON.parse(text);
document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName;
} // end of window.onload function
</script>
<script>
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "numClasses":function () {return 3;}};
myPersonalObject.numClasses = myPersonalObject.numClasses.toString();
var myJSON = JSON.stringify(myPersonalObject);
document.getElementById("myData").innerHTML = myJSON; </script>
The for..in loop is used to get the properties of an object. Since the JavaScript object can be treated as an array, it can be accessed by using the object property.
<h1 id="myData"></h1>
<script>
window.onload = function(){
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
for (x in myPersonalObject) {
document.getElementById("myData").innerHTML += x + "<br>";
}
} // end of window.onload function
</script>
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
for (x in myPersonalObject) {
document.getElementById("myData").innerHTML += x + "<br>";
}
var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
for (x in myPersonalObject) {
document.getElementById("myData").innerHTML += myPersonalObject[x] + "<br>";
}
An object or multiple objects can be nested inside of its parent object.
<h1 id="myData"></h1>
<script>
window.onload = function(){
// Nesting Objects var myWorkObject = {"firstName":"Cornelius",
"lastName":"Chopin",
"title":"Instructor",
"classes": {"class1":"Photoshop",
"class2":"Dreamweaver",
"class3":"Illustrator"} }; document.getElementById("myData").innerHTML = myWorkObject.classes.class1;
} // end of window.onload function
</script>
You can also loop through nested objects. The key is that you have to DRILL DOWN farther into the object.
<h1 id="myData"></h1>
<script>
window.onload = function(){
// Looping Nested Objects ...
} // end of window.onload function
</script>
The delete keyword is used to delete an object's property (duh).
// Deleting an object's property <script>
window.onload = function(){ var myWorkObject = {"firstName":"Cornelius",
"lastName":"Chopin",
"title":"Instructor",
"classes": {"class1":"Photoshop",
"class2":"Dreamweaver",
"class3":"Illustrator"} }; document.getElementById("myData").innerHTML += myWorkObject.classes.class1;
delete myWorkObject.class.class2; for (i in myWorkObject.classes) {
x += myWorkObject.class[i] + "<br>";
}
document.getElementById("myData").innerHTML = x;
} // end of window.onload function
</script>
JSON is commonly used to read data from a web server to display it on a web page. PHP has built-in functions that works with PHP. JavaScript objects can be converted into JSON using the json_encode() function.
<?php
echo phpinfo();
?>
<?php $myObject = new stdClass();
$myObject->firstName = "Cornelius";
$myObject->lastName = "Chopin";
$myObject->title = "Instructor";
$myJSON = json_encode($myObject);
echo $myJSON;
?>
<?php
$myArr = array("Cornelius", "Chopin", "Instructor");
$myJSON = json_encode($myArr);
echo $myJSON;
?>
{"firstName":"Cornelius","lastName":"Chopin","title":"Instructor"}
<!doctype html> <html> <body> <h2>Retrieve JSON from PHP file on server.</h2> <p id="myPHPData"></p>
<script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myJSON = JSON.parse(this.responseText); document.getElementById("myPHPData").innerHTML = myJSON.firstName + " " + myJSON.lastName; } }; xmlhttp.open("GET", "myData.php", true); xmlhttp.send(); </script>
</body>
</html>
JSON HTML content goes here...
JSONP content goes here...
There are alot of SIMILARITIES between JSON and XML. They both:
However, there are some DIFFERENCES betweeen JSON and XML. JSON:
See examples below:
// JSON EXAMPLE {"employees":[
{ "firstName":"Cornelius", "lastName":"Chopin" },
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Mary", "lastName":"Jane" }
]}
NOTE: As part of a name/value pair, notice that "employees" is the name and the value is an array of objects.
// XML EXAMPLE <employees>
<employee>
<firstName>Cornelius</firstName>
<lastName>Chopin</lastName>
</employee>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
<employee>
<firstName>Mary</firstName>
<lastName>Jane</lastName>
</employee>
</employees>
NOTE: It is common practice to use a PLURAL noun (employees) as the top-level node of an XML file and a SINGLE noun (employee) as the repeating nodes.