0

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",
                    }
                ]}
3
  • 1
    jsonText.NewItem = NewValue? Commented Dec 20, 2012 at 11:37
  • As you maybe know, the order of the properties does not matter at all. 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. Commented Dec 20, 2012 at 11:59

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.