DONATE  
MENU
AJAX
HTML
JSON
JAVASCRIPT

JSON Tutorials

INTRODUCTION

» Introduction To JSON

» JSON Format

» JSON Practical Examples

.. » JSON » Introduction » Introduction To JSON
Share Tweet WhatsApp

Introduction To JSON

JSON stands for JavaScript Object Notation. It is basically the standard format for transporting(sending and receiving) data across the internet. The JSON format is used whenever you are storing/sending or receiving from a server a bit complex data that needs further processing. For example, If you are to retrieve a simple data say 1 from a server, you don't necessarily need to encode it in the JSON format as this data can easily be converted from a string to a number and thereafter be use for whatever processing. But what if the data is Stack_ID67SuccessHTML5 where you may need the number (67) contained in the string for whatever processing or outputting. That is where the JSON format comes in... At this point, you should note that only strings or texts can be sent or received from a server. This means if you echo a number say 4 in a PHP script and retrieve that number via AJAX, the data(number) will be sent and received as a string. Example PHP file to output a number - 4
<?php
echo 4;
?>

Copy SEE RESULT

JS codes to retrieve that output
<script>
window.addEventListener("load", retrieveData);

function retrieveData (){
var http = new XMLHttpRequest();
http.open("GET","json_php_20210228121705.php");
http.send();
http.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
alert(typeof(this.responseText));
}
};
}
</script>

Copy PRACTICE IT

Explained Above, we created a PHP file that outputs a number(4) and also a webpage containing some JavaScript codes to retrieve that output via AJAX but as can be seen when the typeof operator was used on the retrieved data(4), the PHP number became a string when received by JS. This example was to further reiterate and help you understand that data are sent and received across servers as strings. This means, whether you send or receive numbers, booleans, strings, arrays, objects, functions and etcetera as data, the data will be sent or received as a string. This therefore means that once it is a string, it can no longer serve the purpose it was initially created for. A function can no longer act as a function when converted to a string as it is now a string. Same goes with numbers, booleans, arrays, objects and etcetera. An example to demonstrate a function can no longer serve as a function once converted to a string.
<script>
var myFunc = function (){
alert(1);
}; //A function

var myFunc2 = function (){
alert(2);
}; //Another function

myFunc = String(myFunc); //First function being converted to a string

myFunc(); //it won't execute because it is no longer a function but a string
myFunc2();
</script>

Copy PRACTICE IT

Therefore, the JSON format enables you to compose data in its format and convert to a string that can be sent and upon receipt, it can thereafter be converted back from a string to its original state. For example, JSON will enable you to send an array say ["67","Success","HTML5"] as a string to a server and it will thereafter enable you to convert it back to its true state as an array after retrieval so that you can access its individual values using the various index keys just as you do with other arrays. JSON stands for JavaScript Object Notation not because it depends on JavaScript for usage but rather because the format is modelled after the JavaScript objects' format. For example, below is a simple javascript object format,
{name: "StackBeginner.com", type: "Tutorial Website", company: "Lectual IT"};
The above is also the standard JSON format for sending and receiving data across servers. The data can then be converted to a string that can be sent and on subsequent receipt or retrieval, it can then again be converted back to an object and be use just the way other objects can be use. Since JSON is not dependent on JavaScript or is platform independent, most programming languages can work with the format. For example, you can use JAVA to retrieve data stored on a server in the JSON format and use various methods of the JAVA language to make it compatible for use in your JAVA program. This is because since JSON is the standard format for transporting data, most programming languages have functions and objects (containing properties and methods) that can be used in encoding data in the JSON format and decoding received JSON format data for use.
<?php
$data = ["name"=>"Mike Tyson", "occupation"=>"Boxing"];
echo json_encode($data);
/*IT WILL DISPLAY
{"name":"Mike Tyson","occupation":"Boxing"}
which is JS objects' format
*/
?>

Copy SEE RESULT

Above, we can see a PHP script using a PHP function (json_encode) to convert a PHP associative array to a JSON format data, which is modelled after the JS object format. That data can then be retrieved and used by JS or any programming language that supports JSON. What does it mean to send and retrieve data from a server? To send or retrieve data from a server can be in various forms but for the purpose of this tutorial, we are simply referring to storing or retrieving data stored on a file in a server. A plain text file can contain some text which can be retrieve by JavaScript using AJAX. A PHP or just any file can do the same. If a PHP file on a server is outputting "Yes" for example, we can retrieve that data from the PHP file using AJAX. That is retrieving data from a server. On the other hand, if we are sending data to a PHP file to process or store, that is sending data to a server. Now, the data we are retrieving or sending can be encoded in the JSON format. You can also send and receive data within JS. For example, you can encode an object as a JSON string and assign it as an argument to a function and subsequently decode back from a string to its original state inside the function.
<script>
//FUNCTION
function displayData(data){
data = JSON.parse(data); //decodes the data from a string
//USING DATA
alert(data["website"]);
}

//PASSING JSON DATA
var data = {name:"StackBeginner", website: "stackbeginner.com"}; //OBJECT
data = JSON.stringify(data); //converts the data to JSON string

displayData(data); //assigning the data as argument to a function
</script>

Copy PRACTICE IT

JavaScript JSON Object Earlier, we've learnt that most programming languages(if not all) have functions or objects(containing methods) that can be used in working with data encoded in the JSON format. The JSON object is the object that enables you to work with data in the JSON format in JavaScript. The JavaScript JSON object is a literal object that contains properties and methods that enables you to manipulate data that are to be sent/encoded or received/decoded in the JSON format.
NOTE:
  • The JSON object is not an objects' prototype but rather a literal object. This means you don't need to create an object from it in order to access its properties and methods.
Its most prominent methods are the stringify() and parse() methods. JSON.stringify() Since we've agreed that data is sent to and fro a server as a string, the stringify() method therefore allows you to convert the data you want to send into a JSON standard string format.
<script>
var obj = {name:"Mr. Mark Edison", position:"MD"};

alert(obj); //[object Object] - because it is an object
obj = JSON.stringify(obj); //converts it to a string which can now be sent
alert(obj);
</script>

Copy PRACTICE IT

Another important use of this method is that it can help you to know the values or elements contained in an object by converting an object to a string. Remember, when you output an object, it returns [object Object] but by converting it to a string with the stringify() method, you can thereafter output and see it values. You will mostly need to do this when writing JS codes.
<script>
var obj = {firstNum:1, secondNum:2, thirdNum:3};
document.write("<b>Without the stringify method</b> "+obj);
var the_str_version = JSON.stringify(obj);
document.write("<br/><br>");
document.write("<b>With the stringify method:</b> "+the_str_version);
</script>

Copy PRACTICE IT

JSON.parse() The parse() method of the JSON object is the opposite of the stringify() method. It helps to convert or decode received JSON string to the original format which can then be use. Example This is a PHP script containing data in a JSON format. We are going to retrieve the data using JS AJAX
<?php
$data = ["name"=>"Nicholas Bulus", "position"=>"Civil Engineer"];
echo json_encode($data);
?>

Copy SEE RESULT

JavaScript codes to retrieve that data and use it in JavaScript
<script>
window.addEventListener("load", retrieveData);

function retrieveData (){
var http = new XMLHttpRequest();
http.open("GET","js_json_20210301102042.php");
http.send();
http.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
var data = this.responseText; //the data in JSON string format
data = JSON.parse(data); //converts from JSON string format to its original format that can then be use
//USING IT
document.write("Engr. "+data["name"]+" is our "+data["position"]);
}
};
}
</script>

Copy PRACTICE IT

SUMMARY
  1. JSON stands for JavaScript Oject Notation.
  2. It s a standard format for transporting(sending & receiving) data across servers.
  3. Usually, all data are sent and received from a server as strings.
  4. JSON gives us a format for arranging a group of data before sending as a string.
  5. This will ensure such data can be made meaningful when received or retrieved.
  6. If data is stored in the JSON format and JavaScript or just any programming language accesses that data, it will be able to convert it not just from a string but also to a state that will enable the usage of the data.
  7. This is because most programming languages including JavaScript usually have functions or an object(containing methods) primarily meant for working with JSON data.
  8. Working with JSON data in any programming language including JS involves two major processes namely Encoding and Decoding.
  9. Encoding involves converting the data from the object form of the programing language to JavaScript object form which is the standard JSON format. For example, PHP will convert from associative arrays to the JSON format. Encoding will also convert the data to a string.
  10. Decoding involves converting an encoded data back not just from a string but also to the object format of the programming language. For example, PHP will convert from the JSON format to PHP associative arrays.
  11. Since the JSON format is modelled after JavaScript object format. By encoding and decoding, JS only need to convert to and fro a string respectively.
  12. The JSON object enables us to work with JSON data in JavaScript. It is a literal object.
  13. The object's stringify() method enables you to encode or convert data to a standard JSON string format which you can then send.
  14. While its parse() method decodes or converts from a string.
Take a short quiz on Introduction To JSON.
Ask a question or tell us if Introduction To JSON is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode