Voice of a Developer: Parse JSON - Part 28

Introduction

 
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, we 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 the 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 an array, list
JSON syntax
  • The data is written as name/value pairs, like JavaScript object properties, e.g.,
    1. {“fname”:”sumit”}   
  • JSON objects are inside curly braces {}, separated by “,”
    1. {“fname”:”sumit”, “lname”:”jolly”}   
  • Arrays are written inside square brackets
    1. {'students': [    
    2. {'name':'Ravi','year':'1st'},    
    3. {'name':'Abhishek','year':'1st'},    
    4. {'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 a lot of baggage and has a lot of opening and closing tags
Easily 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 the 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 the last many years. There is a popular chart depicting the usage of XML vs JSON released by http://www.programmableweb.com/,
 
graph
 

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. 
  1. var json = '{"result":true,"count":1}',    
  2. obj = JSON.parse(json);    
  3. console.log(obj);   
Syntax
  1. JSON.parse(text[, reviver]) 
text: the string to parse a JSON
 

reviver (optional)

 
It is a function to screen or modify values that are being parsed. It is invoked on each data item being parsed, like an iterator. It takes two arguments, like KVP's name and value. You need to address topmost value separately in the reviver call. Example,
  1. JSON.parse('{"fname": "sumit", "lname":"jolly"}'function(k, v) {    
  2. if (k === '') { return v; } // if topmost value, return it,    
  3. console.log(v);    
  4. return v.toUpperCase();     
  5. }); // output will be name in upper case   

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.
 
value
 

JSON.stringify()

 
It converts a JavaScript value to JSON string.
 
Syntax
  1. 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,
    1. var numberJson = ['one''two''three'];    
    2. var json = JSON.stringify(numberJson, function(k,v){     
    3. if (k === '') { return v; }     
    4. console.log(v);    
    5. return v.toUpperCase();     
    6. }, 4);    
    7. console.log(json); // I added 4 characters as whitespace, so below output will be generated   
output
 

Summary

 
My take away from this is JSON over XML and parameters are available in parse and stringify methods. Please share your feedback/comments.


Similar Articles