JSON | modify an array value of a JSON object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in Javascript. Arrays in JSON can have values of following types:
- null
- boolean
- number
- string
- array
- object
The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON.
Array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index.
Example: Modifying the value present at an index in array
<!DOCTYPE html> <html> <body> <p id = "GFG">< /p> <script> var myObj, i, x = ""; myObj = { // stored the values "words":[ "I", "am", "Good" ] }; // modifying the value present at index 2 myObj.words[2] = "bad"; for (i in myObj.words) { // Displaying the modified content x += myObj.words[i] + "<br>"; } document.getElementById("GFG").innerHTML = x; </script> </body> </html> |
Output :
I am bad
Note: If value is modified at an index which is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on.
Example: Modifying the value of index which is out of the array size.
<!DOCTYPE html> <html> <body> <p id = "GFG"></p> <script> var myObj, i, x = ""; myObj = { // stored values "words":[ "I", "am", "Good" ] }; // trying to change a value at // an index out of array size myObj.words[3] = "bad"; for (i in myObj.words) { // display the modification x += myObj.words[i] + "<br>"; } document.getElementById("GFG").innerHTML = x; </script> </body> </html> |
Output :
I am Good bad
Recommended Posts:
- JavaScript | How to add an element to a JSON object?
- Deserializing a JSON into a JavaScript object
- JavaScript | Add new attribute to JSON object
- Converting JSON text to JavaScript Object
- Python | Ways to convert string to json object
- Convert Java Object to Json String using Jackson API
- Convert Json String to Java Object Using GSON
- JavaScript | Check if a key exists inside a JSON object
- Convert Java Object to Json String using GSON
- JavaScript | Convert an array to JSON
- JSON web token | JWT
- Javascript | JSON PHP
- Difference between JSON and XML
- JavaScript JSON
- JSON Formatting in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



