JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let, us look at the previous articles of the series:
In this article, we will understand JSON in detail as a Data Interchange format. Douglas Crockford as “The Fat-Free Alternative to XML” introduced it. We will also understand difference with XML and how could we access it using JavaScript.
JSON (JavaScript Object Notation)
JSON is an easier-to-use alternative to XML. As we know, XML has been there for many years as a data interchange format. XML was better than SGML. We will compare JSON & XML shortly, but before it is good to understand the JSON in detail.
JSON structure
It is built on two structures:
- A collection of name/value pairs.
- An ordered list of values like array, list
JSON syntax
- The data is written as name/value pairs, like JavaScript object properties, e.g.,
- JSON objects are inside curly braces {}, separated by “,”
- {“fname”:”sumit”, “lname”:”jolly”}
- Arrays are written inside square brackets
- {'students': [
- {'name':'Ravi','year':'1st'},
- {'name':'Abhishek','year':'1st'},
- {'name':'Neha','year':'2nd'}]};
Comparison between JSON and XML
It is obvious to compare the two formats:
JSON |
XML |
JSON is less verbose |
XML has lot of baggage and has lot of opening and closing tags |
Easy readable format by humans |
Complex to read large XML files |
JSON is data-oriented |
XML is document-oriented |
JSON notation is built in JavaScript |
XML needs extra library to process it |
JSON is just a data interchange format |
XML is more than interchange format, it’s like a language |
No namespace concept, each object is its own namespace. So names can be repeated |
XML supports namespaces and prefixes |
Each has its own advantages and disadvantages, but JSON is definitely rising for last many years. There is popular chart depicting usage of XML vs JSON released by http://www.programmableweb.com/,
JavaScript JSON parsing
JavaScript contains window.JSON object for parsing JavaScript Object Notation and converting values to JSON. There are two methods associated with it:
JSON.parse()
It can be used to convert a JSON text into Object, e.g.
- var json = '{"result":true,"count":1}',
- obj = JSON.parse(json);
- console.log(obj);
Syntax
JSON.parse(text[, reviver])
text: the string to parse a JSON
reviver (optional)
It is a function to screen or modify values which are being parsed. It is invoked on each data item being parsed, like an iterator. It takes two arguments, like KVP name and value. You need to address topmost value separately in reviver call. Example,
- JSON.parse('{"fname": "sumit", "lname":"jolly"}', function(k, v) {
- if (k === '') { return v; }
- console.log(v);
- return v.toUpperCase();
- });
Syntax Error
In case there is any error in string or reviver then a syntax error is thrown example- I removed on double-quote from lname value.
JSON.stringify()
It converts a JavaScript value to JSON string.
Syntax:
JSON.stringify(value[, replacer[, space]])
value: The value to convert to a JSON string
replacer (optional): This second argument is used to screen and modify the results like reviver in JSON.parse. It accepts KVP name-value pair:
space (optional): We can add number of whitespace characters also,
- var numberJson = ['one', 'two', 'three'];
- var json = JSON.stringify(numberJson, function(k,v){
- if (k === '') { return v; }
- console.log(v);
- return v.toUpperCase();
- }, 4);
- console.log(json);
Summary
My take away from this is JSON over XML and parameters are available in parse and stringify methods. Please share your feedback / comments.