Wednesday, July 25, 2018

Understand and Learn javascript JSON Object with examples

JSON is abbreviated as javascript object notation. Before going to understand javascript JSON object, First, we will go through JSON basics
JSON introduction

  • JSON is a text-based file format that is used to save and transfer data in between software applications. Usually, the browser sends the request data to the server and receive the response data in JSON format.
  • JSON is simple to read and lightweight
  • JSON is language independent. All the programming languages have the support for understanding JSON notation
  • It is only representing data in this format, No methods and functions supported.
  • Comments are not allowed in data JSON Sample

    "name": "Tom",
    "id": "1",
    "age": 25
    "name": "Ram",
    "id": "2",
    "age": 35
JSON Syntax 

JSON object is similar to javascript syntax
JSON object holds key and value pairs separated by a colon. Each object and both key and value pair is separated by a comma.
JSON array is represented using brackets which holds a list of similar elements
Keys only accepts Strings, numbers but not arrays or object arrays
Values can be number,Arrays,String,Objects,boolean,null
Simple JSON example
 var emp={ "name":"Tom" }
JSON Array Example
 var emp=[{ "name":"John" },
{ "name":"Ram" }]
JSON Files

 JSON data can be represented in the form of Strings as well as files. The file extension is json. And content types for this files is application/json.

JSON object in javascript

JSON object is used to manipulate JSON format based files and strings. we can do the convert to/from a string using this method. There are only two methods available in javascript

JSON.parse() method

Take the input as a string and returns the object.
Syntax is JSON.parse(stringObject[, reviver])
stringObject is a string to parse as JSON
reviver - is called during transformation to manipulate key and values and return it.and the return value is the object 
The below are valid strings for parsing into a javascript object
 var jsonString = '{"name": "John","id": "1","age": 25}';
var jsonObject = JSON.parse(jsonString);
console.log(typeof jsonString);// returns string
console.log(typeof jsonObject);// returns object
console.log(jsonString);// returns {"name": "John","id": "1","age": 25}
console.log(jsonObject);// returns Objectage: 25id: "1"name: "John"__proto__: Object
console.log(; // returns John
// valid json parsing
JSON.parse('{}');              // returns {}
JSON.parse('"hello"');           // returns "hello"
JSON.parse('null');            // returns null
JSON.parse('false');            // returns false
json parse example for string reviver
 var test = JSON.parse('{"name":"kiran"}', (key, value) =>{
  return typeof value  === 'string'
    ? value.toUpperCase() // return value in uppercase
    : value     // return everything else unchanged
console.log('t', test); // returns json object like {"name":"KIRAN"}
JSON parse SyntaxError Example 
throws Syntaxerror when unable to parse string format to JSON object.
 Uncaught SyntaxError: Unexpected token ] in JSON at position 
JSON.parse('[4, 1, 9, ]');
JSON.parse('{"key" : "value", }');
Solution or fix to check JSON string format and fix it. You can also check online JSON format validation tools to validate it if required.

JSON Stringify method 

stringify method is used to serialize JSON value as JSON string.
Syntax is JSON.stringify(jsonvalue[, replacer[, space]])
Arguments- jsonvalue is value converted to JSON string
replacer - is a function written to filter/values from full JSON string. keys/values can be omitted using this function. This is optional.
spacer - the third argument can be string or number
And the return value is JSON string
Throws a TypeError ("cyclic object value") exception when a circular reference is found. Valid JSON stringify example
const arrayJson = ['kiran', 'john', 'frank'];
const stringArrayJson = JSON.stringify(arrayJson);
console.log(stringArrayJson); // return ["kiran","john","frank"]
JSON stringify reviver and space example
 const employeeString = {
  id: 1,
  name: 'Kiran',
  age: 35
function replacer(key, value) {
  console.log(typeof value);
  if (key === 'age') {
    return undefined;
  return value;
const empJsonString = JSON.stringify(employeeString, replacer);
console.log(empJsonString) // returns {"id":1,"name":"Kiran"}

const empJsonString1 = JSON.stringify(employeeString, null,'--');
console.log(empJsonString1) // returns {--"id": 1,--"name": "Kiran",--"age": 35}
JSON stringify TypeError error 
we are going to use stringify for the circular reference use case where parent and child objects are referenced. Uncaught TypeError: Converting circular structure to JSON
 const parentObject = {'childObject':null};
parentObject.childObject = parentObject;

Difference between json and jsonp

Plain JSON JSON with padding, JSON data + function call
This works with transferring data from client and server from same domain get the data from a server from the different domain
Content type is application/json Content type is application/javascript
{ "name": "Tom" } function({ "name": "Tom" })
Easy to use and consume it Not simple to understand and use it

How to read data from JSON file in javascript? 

Reading data from JSON file is similar to retrieve data from the Ajax API Call. we can achieve this using XMLHttpRequest or ajax jquery call

  1. Create XMLHttpRequest object
  2. Handles onreadystatechange event- this will be called whenever status changed 
  3. readyState state is 4 and status is 200, request successfully connected and a successful response is returned 
  4. parse data using JSON parse method
  5. onError event is used to handle the errors.
  6. open and send methods are used to connect to resource and send the request to the the server.

   getJSONFileData: function() {
    // XMLHttpRequest read json example
 const xmlRequest = new XMLHttpRequest();
    let path = 'file:///C:/myproject/tsconfig.json';'GET', path, true);
    xmlRequest.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const files = JSON.parse(xmlRequest.response);
      } else {
        console.log('Returned an error while reading json from file');

    xmlRequest.onerror = function() {
      console.log('Error occured during XMLHttpRequest');
    // ajax read json example
  url : 'file:///C:/myproject/tsconfig.json',
  dataType : 'json',
  method : 'GET', 
  success : function(response){
    data = JSON.parse(response);