javascript 向 JSON 字符串添加新属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13971305/
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-26 20:21:00  来源:igfitidea点击:

Add new attribute to JSON string

javascriptjson

提问by TheAlbear

What i can to do is extend my JSON object with a new attrubute.

我能做的是用新的属性扩展我的 JSON 对象。

E.g

例如

  var jsonText = {
            "Repeats": 1,
            "Trials": 4,
            "GroupName": "Mobile phones",
            "targets": [
                    {
                        "name": "Apple",
                    },
                    {
                        "name": "Samsung",
                    }
                ]}

What I would like to end up with is the inclusion of a new item so extend the object so it then looks something like.

我想要结束的是包含一个新项目,以便扩展对象,使其看起来像。

  var jsonText = {
            "NewItem" : NewValue,
            "Repeats": 1,
            "Trials": 4,
            "GroupName": "Mobile phones",
            "targets": [
                    {
                        "name": "Apple",
                    },
                    {
                        "name": "Samsung",
                    }
                ]}

回答by James Allardice

You have a JavaScript object literal, not a JSON string. You can interact with it like a normal object literal:

您有一个 JavaScript 对象文字,而不是 JSON 字符串。你可以像普通的对象文字一样与它交互:

jsonText.NewItem = "NewValue";

If you did actually have a JSON string you could first parse it into a JavaScript object and then handle it in the same way, and then serialize it back into a JSON string. For example:

如果您确实有一个 JSON 字符串,您可以首先将它解析为一个 JavaScript 对象,然后以相同的方式处理它,然后将其序列化回一个 JSON 字符串。例如:

var jsonText = '{ "Repeats": 1, "Trials": 4 }',
    actualObj = JSON.parse(jsonText);
actualObj.newItem = "New Value";
jsonText = JSON.stringify(actualObj);