JavaScript - tutorial - 21 - JSON

revision:


Content

definition and usage JSON syntax JSON data types JSON.parse() JSON.stringify() JSON object literals JSON arrays JSON server JSON PHP JSON HTML JSONP


definition and usage

top

JSON = JavaScript Object Notation: a lightweight text format for storing and transporting data, often used when data is sent from a server to a web page.

Syntax rules: 1. data is in name/value pairs; 2. data is separated by commas; 3. curly braces hold objects; 4. square brackets hold arrays.

example of JSON string:

'{"name":"Walter", "age":"45", "car": null}'

The JSON format is syntactically similar to the code for creating JavaScript objects. Because of this, a JavaScript program can easily convert JSON data into JavaScript objects. Since the format is text only, JSON data can easily be sent between computers, and used by any programming language.

JavaScript has a built in function for converting JSON strings into JavaScript objects: JSON.parse().
JavaScript also has a built in function for converting an object into a JSON string: JSON.stringify().

You can receive pure text from a server and use it as a JavaScript object. You can send a JavaScript object to a server in pure text format. You can work with data as JavaScript objects, with no complicated parsing and translations.


JSON syntax

top

JSON data - a name and a value

JSON data is written as name/value pairs (aka key/value pairs). A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value.

JSON - evaluates to JavaScript objects

The JSON format is almost identical to JavaScript objects. In JSON, keys must be strings, written with double quotes.

example:

{"name":"John"}

In JavaScript, keys can be strings, numbers, or identifier names.

example:

{name:"John"}

JSON values

In JSON, values must be one of the following data types: a string, a number, an object, an array, a boolean, null

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including: a function, a date, undefined

In JSON, string values must be written with double quotes. In JavaScript, you can write string values with double or single quotes.

JSON files

The file type for JSON files is ".json". The MIME type for JSON text is "application/json"


JSON data types

top

In JSON, values must be one of the following data types: a string, a number, an object (JSON object), an array, a boolean, null.
JSON values cannot be one of the following data types: a function, a date, undefined

JSON strings must be written in double quotes: example: {"name":"John"}.

JSON numbers must be an integer or a floating point: example: {"age":30}.

JSON objects : values in JSON can be objects: example: {"employee":{"name":"Theo", "age":30, "city": "Antwerp"}}.

JSON arrays : values in JSON can be arrays: example: {"employees":["Theo", "Liesbeth", "Frank"]}.

JSON booleans : values in JSON can be true/false: example: {"sales":true}.

JSON null : values in JSON can be null: example: {"middlename": null}.


JSON.parse()

top

A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object.

example:

text received from server: '{"name":"John", "age":30, "city":"New York"}'

use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Examples

code:
					<div class="spec">
						<p id="ex1"></p>
						<p id="ex1a"></p>
					</div>
					<script>
						const txt = '{"name":"John", "age":30, "city":"New York"}'
						const obj = JSON.parse(txt);
						document.getElementById("ex1").innerHTML = "text received : " + txt;
						document.getElementById("ex1a").innerHTML = obj.name + ", " + obj.age +", " + obj.city;
					</script>
				

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

Examples

code:
					<div class="spec">
						<p id="ex2"></p>
						<p id="ex2a"></p>
						<p id="ex2b"></p>
					</div>
					<script>
						const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
						const myArr = JSON.parse(text);
						document.getElementById("ex2").innerHTML = "text : " + text
						document.getElementById("ex2a").innerHTML = "array[0] ; " + myArr[0];
						document.getElementById("ex2b").innerHTML = "array[2] ; " +myArr[2];
					</script>
				

Exceptions:

parsing dates : date objects are not allowed in JSON. If you need to include a date, write it as a string. You can convert it back into a date object later. Or, you can use the second parameter of the JSON.parse() function, called reviver. The reviver parameter is a function that checks each property, before returning the value.

convert a string into a date object.

Examples

code:
					<div>
						<p id="ex4"></p>
						<p id="ex4a"></p>
					</div>
					<script>
						const text_a = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
						const obj_a = JSON.parse(text_a);
						obj_a.birth = new Date(obj_a.birth);
						document.getElementById("ex4").innerHTML = "text : " + text_a
						document.getElementById("ex4a").innerHTML = obj_a.name + ", " + obj_a.birth; 
					</script>
				

convert a string into a date object.

Examples

code:
					<div class="spec">
						<p id="ex5"></p>
					</div>
					<script>
						const text_b = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
						const obj_b = JSON.parse(text_b, function (key, value) {
							if (key == "birth") {
								return new Date(value);
							} else {
								return value;
							}
						});
						document.getElementById("ex5").innerHTML = obj_b.name + ", " + obj_b.birth;
					</script>
				

parsing functions : functions are not allowed in JSON. If you need to include a function, write it as a string. You can convert it back into a function later.

convert a string into a function.

Examples

code:
					<div>
						<p id="ex6"></p>
					</div>
					<script>
						const text_c = '{"name":"John", "age":"function() {return 30;}", "city":"New York"}';
						const obj_c = JSON.parse(text_c);
						obj_c.age = eval("(" + obj_c.age + ")");
						document.getElementById("ex6").innerHTML = obj_c.name + ", " + obj_c.age(); 
					</script>
				

JSON.stringify()

top

A common use of JSON is to exchange data to/from a web server. When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify().

example:

object in JavaScript: const obj = {name: "John", age: 30, city: "New York"};

use the JavaScript function JSON.stringify() to convert it into a string: const myJSON = JSON.stringify(obj);

create a JSON string from a JavaScript object.

Examples

code:
					<div>
						<div id="ex7"></div>
					</div>
					<script>
						const obj_1 = {name: "John", age: 30, city: "New York"};
						const myJSON = JSON.stringify(obj_1);
						document.getElementById("ex7").innerHTML = myJSON;
			
					</script>
				

It is also possible to stringify JavaScript arrays.

example:

array in JavaScript: const arr = ["John", "Peter", "Sally", "Jane"];

use the JavaScript function JSON.stringify() to convert it into a string: const myJSON = JSON.stringify(arr);

create a JSON string from a JavaScript array.

Examples

code:
					<div>
						<div id="ex8"></div>
					</div>
					<script>
						const arr = ["John", "Peter", "Sally", "Jane"];
						const myJSON_a = JSON.stringify(arr);
						document.getElementById("ex8").innerHTML = myJSON_a;
			
					</script>
				

Storing data : when storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats. JSON makes it possible to store JavaScript objects as text.

store and retrieve data from local storage

Examples

code:
					<div>
						<div id="ex9"></div>
					</div>
					<script>
						// Storing data:
						const myObj = { name: "John", age: 31, city: "New York" };
						const myJSON_b = JSON.stringify(myObj);
						localStorage.setItem("testJSON", myJSON_b);
						// Retrieving data:
						let text_d = localStorage.getItem("testJSON");
						let obj_d = JSON.parse(text_d);
						document.getElementById("ex9").innerHTML = obj_d.name;
					</script>
				

Exceptions:

stringify dates : in JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.

JSON.stringify() converts date objects into strings.

Examples

code:
					<div>
						<div id="ex10"></div>
					</div>
					<script>
						const obj_e = {name: "John", today: new Date(), city: "New York"};
						const myJSON_c = JSON.stringify(obj_e);
						document.getElementById("ex10").innerHTML = myJSON_c;
					</script>
				

stringify functions : functions are not allowed as object values in JSON. The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value. This can be omitted if you convert your functions into strings before running the JSON.stringify() function.

JSON.stringify() will remove any functions from an object.

Examples

code:
					<div>
						<div id="ex11"></div>
					</div>
					<script>
						const obj_f = {name: "John", age: function () {return 30;}, city: "New York"};
						const myJSON_d = JSON.stringify(obj_f);
						document.getElementById("ex11").innerHTML = myJSON_d;
					</script>
				

JSON.stringify() will remove any functions from an object.

Examples

code:
					<div>
						<div id="ex12"></div>
					</div>
					<script>
						const obj_g = {name: "John", age: function () {return 30;}, city: "New York"};
						obj_g.age = obj_g.age.toString();
						const myJSON_e = JSON.stringify(obj_g);
						document.getElementById("ex12").innerHTML = myJSON_e;
					</script>
				

JSON object literals

top

JSON object literals are surrounded by curly braces {} and contain key/value pairs. Keys and values are separated by a colon. Keys must be strings, and values must be a valid JSON data type: string, number, object, array, boolean, null. Each key/value pair is separated by a comma.

It is a common mistake to call a JSON object literal "a JSON object". JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format. When it is converted to a JavaScript variable, it becomes a JavaScript object.

JavaScript objects : you can create a JavaScript object from a JSON object literal. Normally, you create a JavaScript object by parsing a JSON string.

Examples

creating an object from a JSON literal

creating an object parsing JSON

code:
					<div>
						<p>creating an object from a JSON literal</p>
						<div id="ex13"></div>
						<p>creating an object parsing JSON</p>
						<div id="ex14"></div>
					</div>
					<script>
						//creating an object from a JSON literal
						const myObj_1 = {"name":"John", "age":30, "car":null};
						document.getElementById("ex13").innerHTML = myObj_1.name;
						//creating an object parsing JSON
						const myJSON_1 = '{"name":"John", "age":30, "car":null}';
						const myObj_2 = JSON.parse(myJSON_1);
						document.getElementById("ex14").innerHTML = myObj_2.name;
					</script>
				

Accessing object values : you can access object values by using dot (.) notation. You can also access object values by using bracket ([]) notation.

Examples

dot (.) notation

bracket ([]) notation

code:
					<div>
						<p>dot (.) notation</p>
						<div id="ex15"></div>
						<p>bracket ([]) notation</p>
						<div id="ex16"></div>
					</div>
					<script>
						const myJSON_2 = '{"name":"John", "age":30, "car":null}';
						const myObj_3 = JSON.parse(myJSON_2);
						// dot (.) notation
						document.getElementById("ex15").innerHTML = myObj_3.name;
						// bracket ([]) notation
						document.getElementById("ex16").innerHTML = myObj_3["name"];
					</script>
				

Looping an object : you can loop through object properties with a for-in loop. In a for-in loop, use the bracket notation to access the property values.

Examples

looping object properties

looping JavaScript object values

code:
					<div>
						<p>looping object properties</p>
						<div id="ex17"></div>
						<p>looping JavaScript object values</p>
						<div id="ex18"></div>
					</div>
					<script>
						const myJSON_4 = '{"name":"John", "age":30, "car":null}';
						const myObj_4 = JSON.parse(myJSON_4);
						// looping object properties
						let text_4 = "";
						for (const x in myObj_4) {
							text_4 += x + ", ";
						}
						document.getElementById("ex17").innerHTML = text_4;
						// looping JavaScript object values
						let text_5 = "";
						for (const x in myObj_4) {
							text_5 += myObj_4[x] + ", ";
						}
						document.getElementById("ex18").innerHTML = text_5;
					</script>
				

JSON arrays

top

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

example:

JSON string: '["Ford", "BMW", "Fiat"]'

Inside the JSON string there is a JSON array literal: '["Ford", "BMW", "Fiat"]'

JSON arrays: you can create a JavaScript array from a literal. You can create a JavaScript array by parsing a JSON string:

Examples

creating an array from a literal

creating an array from JSON

code:
					<div>
						<p>creating an array from a literal</p>
						<div id="ex19"></div>
						<p>creating an array from JSON</p>
						<div id="ex20"></div>
					</div>
					<script>
						const myArray = ["Ford", " BMW", " Fiat"];
						//creating an array from a literal
						document.getElementById("ex19").innerHTML = myArray;
						//creating an array from JSON
						const myJSON_z = '["Ford", " BMW", " Fiat"]';
						const myArray_a = JSON.parse(myJSON_z);
						document.getElementById("ex20").innerHTML = myArray_a;			
			
					</script>
				

Accessing array values : you access array values by index.

access an array by index

Examples

code:
					<div>
						<p>creating an array from a literal</p>
						<div id="ex19"></div>
						<p>creating an array from JSON</p>
						<div id="ex20"></div>
					</div>
					<script>
						const myArray = ["Ford", " BMW", " Fiat"];
						//creating an array from a literal
						document.getElementById("ex19").innerHTML = myArray;
						//creating an array from JSON
						const myJSON_z = '["Ford", " BMW", " Fiat"]';
						const myArray_a = JSON.parse(myJSON_z);
						document.getElementById("ex20").innerHTML = myArray_a;			
			
					</script>
				

Arrays in objects : objects can contain arrays and array values are accessed by index.

access array values

Examples

code:
					<div>
						<div id="ex22"></div>
						<div id="ex23"></div>
					</div>
					<script>
						const myJSON_x = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
						const myObj_x = JSON.parse(myJSON_x);
						document.getElementById("ex22").innerHTML = myObj_x.cars[0];			
					</script>
				

Looping through an array : you can access array values by using a for in loop, or Or you can use a for loop.

looping an array

Examples

for in loop

for loop

code:
					<div>
						<p>for in loop</p>
						<div id="ex24"></div>
						<p>for loop</p>
						<div id="ex25"></div>
					</div>
					<script>
						const myJSON_w = '{"name":"John", "age":30, "cars":["Ford", " BMW", " Fiat"]}';
						const myObj_w = JSON.parse(myJSON_w);
						let < = "";
						// for in loop
						for (let i in myObj_w.cars) {
							< += myObj_w.cars[i] + ", ";
						}
						document.getElementById("ex24").innerHTML = <;
						// for loop
						let <w = "";
						for (let i = 0; i < myObj_w.cars.length; i++) {
							<w += myObj_w.cars[i] + ", ";
						}
						document.getElementById("ex25").innerHTML = <w;	
					</script>
				

JSON server

top

Sending data : if you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server.

Receiving data : if you receive data in JSON format, you can easily convert it into a JavaScript object.

sending and receiving data

Examples

sending data

receiving data

code:
					<div>
						<p>sending data</p>
						<div id="ex26"></div>
						<p>receiving data</p>
						<div id="ex27"></div>
					</div>
					<script>
						// sending data
						// const myObj_v = { name: "John", age: 31, city: "New York" };
						// const myJSON_v = JSON.stringify(myObj_v);
						// window.location = "demo_json.php?x=" + myJSON_v;
						// receiving data
						const myJSON_vv = '{"name":"John", "age":31, "city":"New York"}';
						const myObj_vv = JSON.parse(myJSON_vv);
						document.getElementById("ex27").innerHTML = myObj_vv.name;
					</script>
				

JSON from a server : you can request JSON from the server by using an AJAX request. As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.

fetch a JSON file with XMLHttpRequest;

Examples

code:
					<div>
						<div id="ex28"></div>
					</div>
					<script>
						const xmlhttp = new XMLHttpRequest();
						xmlhttp.onload = function() {
							const myObj_u = JSON.parse(this.responseText);
							document.getElementById("ex28").innerHTML = myObj_u.name;
						}
						xmlhttp.open("GET", "json_demo.txt");
						xmlhttp.send();
					</script>
				

Array as JSON : When using the JSON.parse() on JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

fetch a JSON file with XMLHttpRequest;

Examples

code:
					<div>
						<div id="ex29"></div>
					</div>
					<script>
						const xmlhttp_a = new XMLHttpRequest();
						xmlhttp_a.onload = function() {
							const myArr_z = JSON.parse(this.responseText);
							document.getElementById("ex29").innerHTML = myArr[0];
						}
						xmlhttp_a.open("GET", "json_demo_array.txt", true);
						xmlhttp_a.send();
					</script>
				

JSON PHP

top

The PHP file : PHP has some built-in functions to handle JSON. Objects in PHP can be converted into JSON by using the PHP function json_encode().

get JSON data from a PHP server

Examples

code:
					<div>
						<div id="ex30"></div>
					</div>
					<script>
						const xmlhttp_b = new XMLHttpRequest();
						xmlhttp_b.onload = function() {
							const myObj_t = JSON.parse(this.responseText);
							document.getElementById("ex30").innerHTML = myObj_t.name;
						}
						xmlhttp_b.open("GET", "json_demo.php");
						xmlhttp_b.send();
					</script>
				

PHP array : arrays in PHP will also be converted into JSON when using the PHP function json_encode().

PHP method = POST : when sending data to the server, it is often best to use the HTTP POST method. To send AJAX requests using the POST method, specify the method, and the correct header. The data sent to the server must be an argument to the send() method.


JSON HTML

top

JSON can very easily be translated into JavaScript. JavaScript can be used to make HTML in your web pages.

HTML table

			<p id="demo"></p>
			<script>
				const dbParam = JSON.stringify({table:"customers",limit:20});
				const xmlhttp = new XMLHttpRequest();
				xmlhttp.onload = function() {
				const myObj = JSON.parse(this.responseText);
				let text = "<table border='1'>"
				for (let x in myObj) {
					text += "<tr><td>" + myObj[x].name + "</td></tr>";
				}
				text += "</table>"    
				document.getElementById("demo").innerHTML = text;
				}
				xmlhttp.open("POST", "json_demo_html_table.php");
				xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlhttp.send("x=" + dbParam);
			</script>
		

Dynamic HTML table

			<select id="myselect" onchange="change_myselect(this.value)">
				<option value="">Choose an option:</option>
				<option value="customers">Customers</option>
				<option value="products">Products</option>
				<option value="suppliers">Suppliers</option>
			  </select>
			  
			  <p id="demo"></p>
			  
			  <script>
			  function change_myselect(sel) {
				const dbParam = JSON.stringify({table:sel,limit:20});
				const xmlhttp = new XMLHttpRequest();
				xmlhttp.onload = function() {
				  myObj = JSON.parse(this.responseText);
				  text = "<table border='1'>"
				  for (x in myObj) {
					text += "<tr><td>" + myObj[x].name + "</td></tr>";
				  }
				  text += "</table>"    
				  document.getElementById("demo").innerHTML = text;
				}
				xmlhttp.open("POST", "json_demo_html_table.php", true);
				xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlhttp.send("x=" + dbParam);
			  }
			  </script>
		

HTML drop down list

			<p id="demo"></p>
			<script>
				const dbParam = JSON.stringify({table:"customers",limit:20});
				const xmlhttp = new XMLHttpRequest();
				xmlhttp.onload = function() {
				const myObj = JSON.parse(this.responseText);
				let text = "<select>"
				for (let x in myObj) {
					text += "<option>" + myObj[x].name + "</option>";
				}
				text += "</select>"
				document.getElementById("demo").innerHTML = text;
				}
				xmlhttp.open("POST", "json_demo_html_table.php");
				xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlhttp.send("x=" + dbParam);
			</script>
		


JSONP

top

JSONP is a method for sending JSON data without worrying about cross-domain issues. JSONP does not use the XMLHttpRequest object, but it uses the <script> tag instead.

Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage and requests files using the script tag instead of the XMLHttpRequest object.

The server file : the file on the server wraps the result inside a function call. The result returns a call to a function named "myFunc" with the JSON data as a parameter. Make sure that the function exists on the client.

example:

			<?php
				$myJSON = '{"name":"John", "age":30, "city":"New York"}';
				echo "myFunc(".$myJSON.");";
			?>
		

The JavaScript function : the function named "myFunc" is located on the client, and ready to handle JSON data.

example:

			<p id="demo"></p>
			<script>
				function myFunc(myObj) {
				document.getElementById("demo").innerHTML = myObj.name;
				}
			</script>
			<script src="demo_jsonp.php"></script>

		

Creating a dynamic script tag

example:

			<button onclick="clickButton()">Click me!</button>
			<p id="demo"></p>
			<script>
				function clickButton() {
					let s = document.createElement("script");
					s.src = "demo_jsonp.php";
					document.body.appendChild(s);
				}
				function myFunc(myObj) {
					document.getElementById("demo").innerHTML = myObj.name;
				}
			</script>
		

Dynamic JSONP result : the examples above are still very static. Make the example dynamic by sending JSON to the php file, and let the php file return a JSON object based on the information it gets.

example: PHP file

			<?php
				header("Content-Type: application/json; charset=UTF-8");
				$obj = json_decode($_GET["x"], false);

				$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
				$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
				$outp = array();
				$outp = $result->fetch_all(MYSQLI_ASSOC);

				echo "myFunc(".json_encode($outp).")";
			?>
		

example: JavaScript example

			<p id="demo"></p>
			<p>Try changing the table property from "customers" to "products".</p>
			<script>
				const obj = { table: "customers", limit: 10 };
				let s = document.createElement("script");
				s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj);
				document.body.appendChild(s);

			function myFunc(myObj) {
				let txt = "";
				for (let x in myObj) {
					txt += myObj[x].name + "<br>";
				}
				document.getElementById("demo").innerHTML = txt;
			}
			</script>
		

Callback function : when you have no control over the server file, how do you get the server file to call the correct function? Sometimes the server file offers a callback function as a parameter:

example: request With a callback function

			<p>The PHP file returns a call to the function you send as a callback.</p>
			<p id="demo"></p>
			<script>
				let s = document.createElement("script");
				s.src = "demo_jsonp2.php?callback=myDisplayFunction";
				document.body.appendChild(s);
				function myDisplayFunction(myObj) {
					document.getElementById("demo").innerHTML = myObj.name;
				}
			</script>