HomeBlogWeb DevelopmentWorking with Json in Javascript

Working with Json in Javascript

Published
05th Sep, 2023
Views
view count loader
Read it in
7 Mins
Working with Json in Javascript

In this blog we will explore JavaScript Object Notation (JSON) which is derived from JavaScript. JSON is used for data representation similar to XML or YML. It is mainly used while transferring data and data storage, owing to it being lightweight in nature It is used in API communication for sending requests from client and receiving responses from servers over the internet. As JSON is derived from JavaScript anything we write in JSON is a valid JavaScript. All major languages support JSON. They have built-in support to parse JSON strings into object and use JSON in their communication to send requests and receive data. In the coming sections we will explore JSON a bit more and look at its syntaxes.   

What is JSON:-

As stated above, JSON being extremely lightweight can be used with almost all programming languages for communication JSON can reside as file with .json, as an object or we can also use it as String in the programming context. Initially JSON was made for JavaScript but its cross-platform adaptability has made it suitable to work with different programming languages that provide their own set of built-in libraries to support JSON  Just like XML, JSON is a text format but occupies lesser bandwidth than XML and offers faster processing of data. JSON can be built based on the below structures. 

  • Unordered collection of Key/value pairs called as objects. 
Syntax – {“key1” : “value1”, 
                  “key2” : “value2”, …, 
                 “keyN” : “valueN”,              
} 
  •  As an Array, which is an ordered list of values, defined within open ([) and closed (]) brackets separated by comma (,) 

{ 
    "test": [ "value1", 
                   "value2", 
                     ...., 
                    "valueN" 
                 ] 
    } 

 In JSON the keys / property names will always be defined as strings and values can be of any data type. We can also have an object or an array. Below is a sample of JSON object. 

          { 
              "student": { 
                       "studentName": "ABJ Abdul Kalam", 
                       "course": "M.Sc", 
                       "year": 2020, 
                      "studentId": "Msc2020"  
                            } 
        }   

JSON Syntax Rules:- As discussed in the above sections we can define JSON using JSON objects or JSON Arrays 

JSON Object Syntax rules- 

  • JSON object starts with opening and closing curly braces {}. 
  • Keys / Property names defined in object should be String and enclosed within double quotes “ ”.  
  • Values in the object can be any valid data type object or even an array, enclosed within double quotes. 
  • Key and values are separated using colon (:). 
  • We can add multiple key/value pairs. Each key value is separated by a comma (,). 

JSON as an array- Just like in other programming languages, JSON also has similar format in defining the array. An array is a collection of data. 

  • Arrays start with opening ([) and closed (]) bracket. 
  • Values inside the array are separated by comma (,).  

JSON Data Types and Objects:- As in every programming language JSON also has its data types, below are the list of data types which JSON format supports. JSON has 3 types of data types. 

  • JSON Scalar 
  • JSON Array 
  • JSON Object 

JSON Scalar – Can be Number, String, null or Boolean. 

Number  JSON numbers follow JavaScript double-precision floating point format, represented in base 10. Hexadecimal and octal are not supported as numbers in JSON. 

  • Contains digits 0 – 9 
  • We can use negative numbers (-1) 
  • Fractions are also supported (.25) 
  • Supports Exponentiation 
  • No support for hexadecimal and octal 
Ex --  
     {  
       "num”: 100, 
       "num1”: -10, 
       "num2”: 10.23, 
       "num3”: 2.0E+4 
     } 

String  String is a collection of characters enclosed within double quotes (“ “). 
       Ex --  

        { 
            “name” : “KnowledgeHut” 
           } 

     JSON strings support the below list of escaped / back slack characters. 

 \" – Double quote 
\b – Backspace 
\t – Tab 
\u – Trailed by four hex digits 
\\ – Backslash 
\n – Newline 
\/ – Forward slash 
\f – Form feed 
\r – Carriage return 

 Boolean -- JSON supports boolean values which can be either true/false. 
Ex --

         { 
            “flag” : true 
          } 

Null  When we do not assign any value to the key it is known as null. 
    Ex – 

  { 
            “flag” :  //empty 
          } 

JSON Array:- JSON array is an order collection of data, that starts with open ([) and ends with (]) brackets, values inside the array are separated by commas (,). 

Ex-  

    { 
      “vegetables” : [“potato”,”tomato”,”brinjal”,”cucumber”] 
   } 

JSON Object:-  As object is a collection of unordered key/value pairs. They start with opening and closing curly braces {} and all the Keys / Property names defined in object should be String and enclosed within double quotes “ ”. The values in the object can be any valid data type, object or even an array, enclosed within double quotes. Keys and values are separated using colon (:) and wcan add multiple key/value pairs, each key value is separated by a comma (,). 

          { 
              "student": { 
                       "studentName": "ABJ Abdul Kalam", 
                       "course": "M.Sc", 
                       "year": 2020, 
                      "studentId": "Msc2020"  
                            } 
        }   

JSON Arrays and Functions:-  

An array is a collection of data; and JSON arrays too are an order collection of data that start with open ([) and end with (]) brackets, with values inside the array being separated by comma (,). 

  • Array in JSON is defined within the brackets [ ]. 
  • Arrays can store multiple values 
  • Supports different data types 
  • All the values in array must be separated by comma (,). 
  • Index in array always starts with 0. 

Ex- 

{ 
      “vegetables” : [“potato”,”tomato”,”brinjal”,”cucumber”] 
 } 

How to get value of any array – by using index number we can access an array. 

Ex- 

 { 
      “vegetables” : [“potato”,”tomato”,”brinjal”,”cucumber”] 
 } 

a = myObj.vegetables[0] àoutput àpotato. 

How to delete value in an array – by using the keyword delete we can delete the value in the given array. 

Ex- 

{ 
      “vegetables” : [“potato”,”tomato”,”brinjal”,”cucumber”] 
 } 

delete myObj.vegetables[1]; à deletes the value in array at index 1, which is tomato. 

Updating value in the array – We can update the value in the given array by using the keyword update. 

Ex 

{ 
      “vegetables” : [“potato”,”tomato”,”brinjal”,”cucumber”] 
 } 
myObj.vegetables[2]=”lettuce”; 
Looping in Array  using for-in loop we can access all the values in the array. 
{ 
      “vegetables” : [“potato”,”tomato”,”brinjal”,”cucumber”] 
 } 
for(x in myObj.vegetables){ 
   y = myObj.vegetables[x] 
   console.log(y); 
}  

Output    

potato       
tomato  
brinjal 
cucumber 

Multi-dimensional Array An array defined inside another array is known as multi-dimensional array. 

Ex- 

var emp = { 
    "employerName  : "KnowledgeHut", 
    "empDept" : [  
                [ "administrators", "Ravi", "Kamal" , "Divya"], 
                    [ "HR", "Dheeraj", "Kapil" , "Sanjana"], 
               ] 
} 
for (x in emp.empDept) { 
   for (y in emp.empDept[x]) { 
        z = emp.empDept[x][y]; 
       console.log (z);  
    }  
} 

Output 

administrators 
Ravi 
Kamal 
Divya 
HR 
Dheeraj 
Kapil 
Sanjana 

JSON Functions:- In order to convert object to string and string to object, JSON provides two functions. 

  •  JSON.stringify() – Used to convert JavaScript objects to JSON strings. It is used to serialize a JavaScript object into JSON string. 
  •  JSON.parse() – As the name suggests, we use this to parse the data that is received as JSON.  It is used to de-serialize JSON String to JavaScript  objects.

JSON.stringify() - 
   Ex –  

var emp = {"empFirstName" : "APJ Abdul", "empLastName" : "Kalam", "empLocation" : "India"} 
var x = JSON.stringify(emp) , now we have converted JavaScript Object to JSON Strings. Using x we can work on this string. 

  JSON.parse()- 

var jsonString = '{ "empName": "KnowledgeHut", "address": "India" }'; 
var obj = JSON.parsejsonString );   
console.log(obj); 
Converting JSON to a JavaScript Object:-  
        JSON.parse() – As the name suggests, we use this to parse the data that is received as JSON. Parse function is used to de-serialize JSON String to JavaScript objects. 
Syntax -- var obj = JSON.parse(JSON); 
<html> 
    <body> 
        <script> 
              var json = '{"empFirstName": "APJ Abdul", "empLastname": "Kalam", "empState":      "Mumbai"}'; 
 
var obj = JSON.parse(json); 
document.write(obj.empFirstName); 
document.write(obj.empLastname); 
document.write(obj.empState); 
      </script> 
</body> 
</html> 

Converting JavaScript Object to JSON:- In order to convert JavaScript Object to JSON string we can simply use JSON.stringify(). 

Syntax --  JSON.stringify(value, replacer, space) 

Value -- any JavaScript value, usually an object or array. 
replacer-- an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. 
space -- an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. 

var x = { 
  "webSite": "KnowledgeHut" 
      }; 
console.log(JSON.stringify(x));  

Conclusion:-

JSON which is the short form of JavaScript Object Notion is one of the most popular data transition formats. JSON was originally designed for JavaScript to be used in data exchange, owing to ittext-based format which makes it easier to read/write and its lightweight property which makes it a stress-free alternative for machines to serialize/de-serialize. Because of these properties, all the programming languages have created their own built-in libraries to support JSON. Its unique properties and language independence make it the ideal choice for data-interchange operations or for building APIs.  

Profile

Bala Krishna Ragala

Blog Author

Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

Share This Article
Ready to Master the Skills that Drive Your Career?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)

Upcoming Web Development Batches & Dates

NameDateFeeKnow more
Course advisor icon
Course Advisor