How do i add new attribute (element) to JSON object using javascript?

share|improve this question
48  
Accept the answer and close this question – Arun P Johny Sep 16 '09 at 17:16
3  
Sorry folks, moderators do not have the ability to accept an answer on questions they do not own. – Tim Post Sep 11 '11 at 13:11

4 Answers

JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.

To add a property to an existing object in JS you could do the following.

object["property"] = value;

or

object.property = value;

If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.

share|improve this answer
var jsonObj = {
    members: 
           {
            host: "hostName",
            viewers: 
            {
                user1: "value1",
                user2: "value2",
                user3: "value3"
            }
        }
}

var i;

for(i=4; i<=8; i++){
    var newUser = "user" + i;
    var newValue = "value" + i;
    jsonObj.members.viewers[newUser] = newValue ;

}

console.log(jsonObj);
share|improve this answer

A JSON object is simply a javascript object, so with Javascript being a prototype based language, all you have to do is address it using the dot notation.

   mything.NewField = 'foo';
share|improve this answer

Hi, thanks for this post. I want to add something that can be useful.

For IE, it is good to use object["property"] = value; syntax because some special words in IE can give you an error. An example: object.class = 'value'; this fails in IE, because "class" is a special word. I spent several hours with this................!

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.