JSON Server
- Previous Page JSON Array
- Next Page JSON PHP
A common use of JSON is to exchange data with web servers.
When receiving data from a web server, the data is always a string.
With JSON.parse()
Parse the data, and it will become a JavaScript object.
Send Data
If you store data in a JavaScript object, you can convert the object to JSON and send it to the server:
Example
const myObj = {name: "Bill", age: 31, city: "New York"}; const myJSON = JSON.stringify(myObj); window.location = "demo_json.php?x=" + myJSON;
Receive Data
If you receive data in JSON format, you can easily convert it into a JavaScript object:
Example
const myJSON = '{"name":"Bill", "age":31, "city":"New York"}'; const myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name;
JSON from the server
You can request JSON from the server using AJAX requests
As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.
Example
Use XMLHttpRequest to retrieve data from the server:
const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; }; xmlhttp.open("GET", "json.txt"); xmlhttp.send();
Please see:json.txt
JSON in array form
Using JSON.parse()
This method will return a JavaScript array instead of a JavaScript object when called with an array derived JSON.
Example
JSON returned from the server as an array:
const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr[0]; } } xmlhttp.open("GET", "json_array.txt", true); xmlhttp.send();
Please see:json_array.txt
- Previous Page JSON Array
- Next Page JSON PHP