Working With Arrays In JSON

JSON is a language that is used for exchanging data between a web application and the database.

JSON

In this article, we will learn about  working with arrays. In my last article we learned the basic definition of JSON language, objects and working with objects.

  • JSON Definition
  • JSON arrays
  • Syntax
  • Example
  • Accessing elements
  • Looping through arrays

JSON definition

JSON is a language that is used for exchanging data between web applications and the database. JSON is a text and we can convert any Java Script into object and JSON to server.

It’s a light weight data interchange format.

JSON arrays

Array is known as collection of same data types (i.e.Homogenous). An array may contain same data type of integer or string. Arrays are commonly used for storing values. However there are certain disadvantages in the array once the array size is declared the array size can’t be increased or reduced. The array index starts from zero.

The arrays in JSON is similar as in Java Script.The syntax of the array is given below

Array Syntax

[value,value,value,value]

Array Example

  1. [“Mavi”,”Ravi”,” Siva”]  

Array can be value of an object property

  1. {“  
  2.     name”: “Ravi”,  
  3.     “age”: 35,  
  4.     “friends”: [“Raj”, ”Mani”]  
  5. }  

Accessing Array Values

Inside the script tag:

  1. var tobj, i;  
  2. tobj = {“  
  3.     name”: ”Ravi”,  
  4.     “age”: 35,  
  5.     “friends”: [“Raj”, ”Mani”]  
  6. }  
  7. i = tobj.friends[0];  
  8. document.getElementById(“id name”).innerHTML = i; 

The output of the program is given below

Output: Raj

To access whole array element we can use for loop

For example:

  1. For(x in tobj.friends)   
  2. {  
  3.     a += tobj.friends[x] + ” < br > ”;  
  4. }  
  5. Document.getElementById(“id name”).innerHTML = a;  

The output of the above code is

Raj

Mani

Modify array values

The array values can be easily modified

For example

From the above data suppose if we want to edit the value it can be done like this:

  1. <html>  
  2.   
  3. <body>  
  4.     <p>Changing Array values</p>  
  5.     <p id=”my”></p>  
  6.     <script>  
  7.         var tobj, a, b = ”“;  
  8.         tobj = {“  
  9.             name”: ”Ravi”,  
  10.             “age”: 35,  
  11.             “friends”: [“Raj”, ”Mani”]  
  12.         };  
  13.         tobj.friends[0] = ”Charles”;  
  14.         for (a in tobj.friends) {  
  15.             b += tobj.friends[a] + ” < br > ”;  
  16.         }  
  17.         document.getElementById(“my”).innerHTML = b;  
  18.     </script>  
  19. </body>  
  20.   
  21. </html>  

The output of the code is

  • Charles
  • Mani

Delete the Array Values

By using the delete keyword it is easy to delete the array value

  1. delete tobj.friends[1];  

Conclusion

I hope this article will give you a little knowledge about JSON arrays. In the next article we will see a little more advanced techniques in  JSON.