JSON Server
JSON is often used to send and receive data with a web server.
When data comes from a web server, it is always in the form of text.
To understand the text, you can use JSON.parse()
. This function helps convert the data into a JavaScript object.
Receiving Data
If you get data in JSON format, you can quickly change it into a JavaScript object.
JSON From a Server
You can ask the server for JSON data by making an AJAX request.
If the server sends back information in JSON format, you can change that information into a JavaScript object.
Array as JSON
If you use JSON.parse()
on JSON that comes from an array, it will give you a JavaScript array, not a JavaScript object.
<!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>
<!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>
<!DOCTYPE html>
<html>
<body>
<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p>Content written in a JSON array changes 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>