JSON is short for JavaScript Object Notation, and is a way to store information in an organized, easy-to-access manner. In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner.
Exchanging Data
When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:
Example: var myObj = {name: “John”, age: 31, city: “New York”};
var myJSON = JSON.stringify(myObj);
window.location = “demo_json.php?x=” + myJSON;
Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:
Example: var myJSON = ‘{“name”:”John”, “age”:31, “city”:”New York”}’;
var myObj = JSON.parse(myJSON);
document.getElementById(“demo”).innerHTML = myObj.name;
Why use JSON?
Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any programming language.
JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:
JSON.parse()
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
Example: {“employees”:[
{ “firstName”:”John”, “lastName”:”Doe” },
{ “firstName”:”Anna”, “lastName”:”Smith” },
{ “firstName”:”Peter”, “lastName”:”Jones” }
]}