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
Array can be value of an object property
- {“
- name”: “Ravi”,
- “age”: 35,
- “friends”: [“Raj”, ”Mani”]
- }
Accessing Array Values
Inside the script tag:
- var tobj, i;
- tobj = {“
- name”: ”Ravi”,
- “age”: 35,
- “friends”: [“Raj”, ”Mani”]
- }
- i = tobj.friends[0];
- 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:
- For(x in tobj.friends)
- {
- a += tobj.friends[x] + ” < br > ”;
- }
- 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:
- <html>
-
- <body>
- <p>Changing Array values</p>
- <p id=”my”></p>
- <script>
- var tobj, a, b = ”“;
- tobj = {“
- name”: ”Ravi”,
- “age”: 35,
- “friends”: [“Raj”, ”Mani”]
- };
- tobj.friends[0] = ”Charles”;
- for (a in tobj.friends) {
- b += tobj.friends[a] + ” < br > ”;
- }
- document.getElementById(“my”).innerHTML = b;
- </script>
- </body>
-
- </html>
The output of the code is
Delete the Array Values
By using the delete keyword it is easy to delete the array value
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.