How to Add New Property to JSON Object Using JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the Dot/Square Bracket Notation
You can simply use the dot (.
), or square bracket ([]
) notation to add a new element or property to JSON Object using JavaScript. JSON is basically a string whose format very much resembles to JavaScript object. See the tutorial on JavaScript JSON Parsing to learn more about it.
Let's take a look at the following example to understand how it basically works:
Example
Try this code »// 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);
Related FAQ
Here are some more FAQ related to this topic: