Introduction
The following describes JSON:
- JSON is a lightweight data-interchange format.
- JSON is a self-describing and easy to understand and easier to use alternative to XML.
- JSON is language-independent.
The following are some rules of JSON Syntax:
- JSON data consists of name/value pairs.
- In JSON data is separated by commas.
- In JSON Curly Braces hold objects.
- In JSON Square Braces hold arrays.
JSON Data Syntax
JSON data consist of name and value pairs. It consists of a field name in double quotes (""), then a colon then a value.
JSON values can be a number, a string, a Boolean, an array, an object or null.
JSON objects can contain multiple name/values pairs written inside Curly Braces.
A JSON array can contain multiple objects and are written inside Square Braces.
In this example, the object "students" is an array containing three objects. Each object is a record of a student.
Example: JSON Object Creation in JavaScript.
- <!DOCTYPE html>
- <html>
- <body>
- <h2>JSON Object Creation</h2>
- <p id="Result"></p>
-
- <script>
- var obj = JSON.parse('{"Company_Name":"C-SharpCorner","Address":"Noida","phone":"XXXXXX"}');
-
- document.getElementById("Result").innerHTML =
- obj.Company_Name+ "<br>" +
- obj.Address+ "<br>" +
- obj.phone;
- </script>
-
- </body>
- </html>
The following is the output of that:
XML has to be parsed with an XML parser, whereas JSON can be parsed by a standard JavaScript function.
The following is an XML example of student objects with 3 student records:
- <students>
- <student>
- <firstName>Shalin</firstName> <lastName>Dashora</lastName>
- </student>
- <student>
- <firstName>Milan</firstName> <lastName>Jain</lastName>
- </student>
- <student>
- <firstName>Priyanshi</firstName> <lastName>Dashora</lastName>
- </student>
- </students>
Similarities and Differences between JSON and XML
Similarity
- Both JSON and XML are self-describing.
- Both JSON and XML are hierarchical.
- Both JSON and XML can be parsed and used by many programming languages.
- Both JSON and XML can be fetched with an XMLHttpRequest.
Differences
- JSON doesn't use an end tag.
- JSON is shorter.
- JSON is quicker to read and write.
- JSON can use arrays.
- JSON is faster and easier, for AJAX applications.
- XML Extracts values and stores them in variables.
- JSON parses JSON strings.