Skip to content Skip to sidebar Skip to footer

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', si

Solution 1:

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";

Solution 2:

As long as the user variable is in scope:

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

Solution 3:

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

Solution 4:

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.

Post a Comment for "Replacing A Property Value In Json"