Definition
- Used for storing and exchanging data (application communication) over the internet. A light-weight data interchange format
- Language independent
- Self describing
- Hierarcichal
JSON vs XML
// JSON
{"employees":[
{"firstName":"Roger", "lastName":"Rabbit"},
{"firstName":"Donald", "lastName":"Duck"}
]}
// XML
<employees>
<employee>
<firstName>Roger</firstName>
<lastName>Rabbit</lastName>
</employee>
<employee>
<firstName>Donald</firstName>
<lastName>Duck</lastName>
</employee>
</employees>
They both:
- Are self describing
- Are hierarchical (nested values)
- Can be be fetched from the XMLHttpRequest
- Can be parsed and used by almost all programming languages
JSON is unlike XML in that:
- It's shorter
- It's easier to read and write
- It doesn't require an end-tag
- It CAN use arrays
- XML needs to be parsed by an XML parser while JSON can be parsed by a standard JavaScript function
Syntax
- Data is in name/value pairs
"firstName":"Tony"- Data is seperated by commas
"firstName":"Tony","lastName":"Stark"- Curly braces hold objects
{"firstName":"Tony","lastName":"Stark"}- Square brackets hold arrays
[{"firstName":"Tony","lastName":"Stark"},
{"firstName":"Donald","lastName":"Duck"}]
JavaScript Parsing
// Out HTML element to plug the data into
<p id="demo"></p>
<script>
// name/value pairs are seperated with ':'
// Different properties are seperated with ','
// One object is shown using {}
// You MUST use double quotes around names/values
var jsonText = '{"name":"Jack Johnson","street":"123 Maple street","phone":"234-234-4568"}';
// Use javaScript's JSON object to parse our jsonText
// into something we can use in javascript/html
var jsonObj = JSON.parse(jsonText);
// Output our data
document.getElementById().innerHTML = jsonObj.name + "
" + jsonObj.street + "
" + jsonObj.phone;
</script>