开发者

Replacing a property value in JSON

If I have a JSON structure that looks something like this:

var user = {
    map: {
        width: 785,
        height: 791
    },
    image: {
        name: "image.png",
        size: {width:32}
    },
    properties:[{
        firstName: "Bob",
        lastName: "Jones",
    }]
};

How 开发者_开发百科would I change (after creation) the value of the firstName property to "Jane"?

I am fairly new to JSON, and I'm just trying to figure out how to make this one change for now. Any help would be greatly appreciated.


Well, one reason for your confusion might be that this is not JSON at all. JSON is a text format used for serialising objects. This is just a literal object in Javascript.

To change the firstName property, you would access the first item in the properties array in the user object:

user.properties[0].firstName = "Jane";


As long as the user variable is in scope:

user.properties[0].firstName = "Jane";


var changeName = function(obj, newName) {
   obj.properties[0].firstName = newName;
   return obj;
}


I saw this question and the solutions to it but my script still didn't work. I found the solution and I figured I should post this here, it might save some people a little research.

My JSON result had some integers in it and it required the parseInt() function.

Taking the above example you probably have to do something like this.

user.map.width = parseInt(somevariable);

Since javascript is loosely typed I never really worry about it, but in this case it's necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜