admin管理员组

文章数量:1296884

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

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",
                    }
                ]}

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

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",
                    }
                ]}
Share Improve this question asked Dec 20, 2012 at 11:34 TheAlbearTheAlbear 5,5958 gold badges54 silver badges85 bronze badges 3
  • 1 jsonText.NewItem = NewValue? – Pekka Commented Dec 20, 2012 at 11:37
  • As you maybe know, the order of the properties does not matter at all. – Alberto De Caro Commented Dec 20, 2012 at 11:54
  • I know the order doesn't matter, I added it at the start to make it more obvious to see the result I was looking for. – TheAlbear Commented Dec 20, 2012 at 11:59
Add a ment  | 

1 Answer 1

Reset to default 6

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

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:

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

本文标签: javascriptAdd new attribute to JSON stringStack Overflow