JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JSON Server
JSON is used 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.
Sending Data
If data is stored in a JavaScript object, convert the object into JSON, and send it to a server.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Convert a JavaScript object into a JSON string, and send it to the server.</h2>
<script>
const myObj = { name: “John”, age: 31, city: “New York” };
const myJSON = JSON.stringify(myObj);
window.location = “demo_json.php?x=” + myJSON;
</script>
</body>
</html>
Output
demo_json.php:
John from New York is 31
Receiving Data
If you receive data in JSON format, convert it into a JavaScript object:
Example
<!DOCTYPE html>
<html>
<body>
<h2>Convert a JSON string into a JavaScript object.</h2>
<p id=”demo”></p>
<script>
const myJSON = ‘{“name”:”John”, “age”:31, “city”:”New York”}’;
const myObj = JSON.parse(myJSON);
document.getElementById(“demo”).innerHTML = myObj.name;
</script>
</body>
</html>
Output
Convert a JSON string into a JavaScript object.
JSON From a Server
JSON can be requested 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.
Example
Use the XMLHttpRequest to get data from the server.
<!DOCTYPE html>
<html>
<body>
<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p id=”demo”></p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById(“demo”).innerHTML = myObj.name;
}
xmlhttp.open(“GET”, “json_demo.txt”);
xmlhttp.send();
</script>
</body>
</html>
Output
Fetch a JSON file with XMLHttpRequest
John
Array as JSON
While using the JSON.parse() on JSON is derived from an array, the method returns a JavaScript array, instead of a JavaScript object.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p>Content written as a JSON array will be converted into a JavaScript array.</p>
<p id=”demo”></p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myArr = JSON.parse(this.responseText);
document.getElementById(“demo”).innerHTML = myArr[0];
}
xmlhttp.open(“GET”, “json_demo_array.txt”, true);
xmlhttp.send();
</script>
</body>
</html>
Output
Fetch a JSON file with XMLHttpRequest
Content written as a JSON array will be converted into a JavaScript array.
Ford