Menu

Showing posts with label JSON object. Show all posts
Showing posts with label JSON object. Show all posts

update a JSON object using JavaScript

JSON objects are frequently used as a data format in the web world. Many times, we encounter situations where we need to update the JSON object or a part of the JSON object (JSON object property). In this blog, we will discuss how to update a part of a JSON object using JavaScript.

For example, we have a json object that have dimentions.

let dimensions = [

    {"height": 100, "width": 50},

    {"height": 200, "width": 150},

    {"height": 300, "width": 250},

    {"height": 400, "width": 350}

  ]

Supoose we now need to update the first width of the first diemension in the object. First check the current value with below statement.

dimensions[0].width

This will return 50. Since, the width of first diemnsion index is 50.  

Now update the value of width from index 0.

dimensions[0].width = '90'

For example, we have update the value with 90. Now, when you access the width value from index 0, it will return 90. Try accessing the first object from dimentions array object.

dimensions[0]

This will retun first object which is now updated width value. 

{

    "height": 100,

    "width": "90"

}

 

Below is the screenshot of the updating JSON object property use-case.

Update JSON object using JS
Update JSON object using JS


Create JS Object from JSON text

How to traverse on JSON (JavaScript object notation) object using JavaScript and how to traverse JSON array using JavaScript?

Below is the simple HTML and JavaScript based program, which have a JSON data object and further that json object have json array. Using JavaScript we will read that json data one by one and generate output for end user, and later that output we will show on html page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
<body>
<h2>Create JS Object from JSON String</h2>
 <p id="output">
 </p>
<script>
var txt = '{"employees":[' +
'{"firstName":"Rashid","lastName":"Jorvee" },' +
'{"firstName":"Java","lastName":"Script" },' +
'{"firstName":"Node","lastName":"JS" }]}';


var jsonData = JSON.parse(txt);
var output="";
for (var i = 0; i < jsonData.employees.length; i++) {
    var counter = jsonData.employees[i];
    console.log(counter.firstName);
    output += "First name: " +  counter.firstName +  ", Last Name: " +counter.lastName +"<br />";
 document.getElementById("output").innerHTML = output;
   
}

</script>
</body>
</html>

Output:

Create JS Object from JSON String

First name: Rashid, Last Name: Jorvee
First name: Java, Last Name: Script
First name: Node, Last Name: JS

Output on browser console: 

console output on browser debugger console
console output on browser debugger console