13

I create JSON object as:

var myJsonObject = JSON.stringify(objectString)

How I can add another item into myJsonObject??

1
  • are you sure you need JSON.stringify()? don't you mean JSON.parse()? Commented Jan 28, 2013 at 16:10

3 Answers 3

18

myJsonObject is now a string you cannot add anything to it again until you change it back into a JSON object.

So you can technically do:

var myJsonObject = JSON.parse(myJsonObject); //change to obj
myJsonObject.somethingnew = true; //add something
myJsonObject = JSON.stringify(myJsonObject); //change back to string
Sign up to request clarification or add additional context in comments.

Comments

7

Looks like you're re-serializing the string rather than parsing it.

var myJsonObject = JSON.parse(objectString);

then you can add a new item by using

myJsonObject['newItemName'] = newValue;

Hope that's clear.

Comments

3

If you mean you want to have an array of objects, you can do it like this:

//create an array with the result of your object (see the [] characters)
var myJsonArrayObject = JSON.stringify( [ objectString ] );

//add a new element to the array: parse the JSON, push the new element and stringify again:
JSON.stringify( JSON.parse( myJsonArrayObject ).push( newObject ) );

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.