Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Add New Element to JSON Object</title> </head> <body> <script> // Store JSON string in a JS variable var json = '{"name": "Harry", "age": 18}'; // Converting JSON-encoded string to JS object var obj = JSON.parse(json); // Adding a new property using dot notation obj.gender = "Male"; // Adding another property using square bracket notation obj["country"] = "United States"; // Accessing individual value from JS object document.write(obj.name + "<br>"); // Prints: Harry document.write(obj.age + "<br>"); // Prints: 14 document.write(obj.gender + "<br>"); // Prints: Male document.write(obj.country + "<br>"); // Prints: United States // Converting JS object back to JSON string json = JSON.stringify(obj); document.write(json); </script> </body> </html>