javascript 替换 JSON 中的属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6418814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:36:05  来源:igfitidea点击:

Replacing a property value in JSON

javascriptjson

提问by simmB

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

如果我有一个看起来像这样的 JSON 结构:

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 firstNameproperty to "Jane"?

我将如何(创建后)将firstName财产的价值更改为“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.

我对 JSON 相当陌生,我现在只是想弄清楚如何进行这一更改。任何帮助将不胜感激。

回答by Guffa

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.

好吧,您感到困惑的一个原因可能是这根本不是 JSON。JSON 是一种用于序列化对象的文本格式。这只是 Javascript 中的一个文字对象。

To change the firstNameproperty, you would access the first item in the propertiesarray in the userobject:

要更改firstName属性,您将访问对象properties数组中的第一项user

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

回答by user113716

As long as the uservariable is in scope:

只要user变量在范围内:

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

回答by alex

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

回答by BBQ

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.

我的 JSON 结果中有一些整数,它需要 parseInt() 函数。

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.

由于 javascript 是松散类型的,我从不真正担心它,但在这种情况下它是必要的。