158

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:

 {"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}

I want to add a new item to the array, such as

{"teamId":"4","status":"pending"}

to end up with

{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}

before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.

6
  • 7
    yourObj.theTeam.push({"teamId":"4","status":"pending"});
    – PSL
    Commented Sep 19, 2013 at 1:18
  • 1
    When you read the JSON object from the file, is it being interpreted as JSON or a string? If its a string you need to parse the string as JSON first then you can do what the other comment and answer are suggesting.
    – Mark
    Commented Sep 19, 2013 at 1:20
  • @brad - I didn't say JSON was an object - I said I had a JSON format object. Thanks for the quick response. Commented Sep 19, 2013 at 1:23
  • 3
    @Charles read your title and then reexamine your comment. Commented Sep 19, 2013 at 1:24
  • 1
    @CharlesWyke-Smith What type is your teamJSON variable? Is it a JSON string, ie '{"theTeam":[...]}' or an actual object literal? Hint: use console.log(typeof teamJSON)
    – Phil
    Commented Sep 19, 2013 at 1:32

6 Answers 6

303

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
8
  • 23
    +1 for pointing out this needs to be parsed in to an object first to be manipulated. Commented Sep 19, 2013 at 1:21
  • 3
    He said he already has the object in a variable named teamJSON. At no point is a string mentioned
    – Phil
    Commented Sep 19, 2013 at 1:23
  • 9
    @Phil: If it's JSON, it's a string. If it's not, it's not JSON. Commented Sep 19, 2013 at 1:25
  • 1
    The escaped quotes actually makes me wonder if the JSON was encoded twice. Commented Sep 19, 2013 at 1:26
  • 31
    Paul, that is a very constructive answer. It addresses the deficiency in the problem statement without belittling the original poster. It more clearly delineates the boundaries between operating on the javascript objects and the JSON text representation of those objects. I think it is essential in understanding that once the JSON has been parsed, we are operating on pure javascript objects -- the fact that they originally came from JSON is irrelevant. Anyway, reading your answer was a breath of fresh air after all the derogatory comments making the OP feel like an idiot. Commented Feb 25, 2014 at 13:40
28
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

If you want to add at last position then use this:

var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

If you want to add at first position then use the following code:

var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"

Anyone who wants to add at a certain position of an array try this:

parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"

Above code block adds an element after the second element.

2

First we need to parse the JSON object and then we can add an item.

var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);

Finally we JSON.stringify the obj back to JSON

2
  • What if our JSON doesn't have a name like theTeam, but instead only contains nodes with the elements teamId & status? so mine would look like: var str = '[{"teamId":"1","status":"pending"}, {"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]';
    – Shafique
    Commented Feb 12, 2020 at 19:18
  • Shafique: Then it's even easier. Just remove the ['theTeam']. portion after obj. So: obj.push(...)
    – ultrageek
    Commented Sep 16, 2020 at 2:41
2

In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.

  elementToPush = [1, 2, 3]
  if (!obj.arr) this.$set(obj, "arr", [])
  obj.arr.push(elementToPush)  

(This answer may not be relevant to this particular question, but may help someone else)

1

Use spread operator

    array1 = [ 
    {
                "column": "Level",
                "valueOperator": "=",
                "value": "Organization"
            } 
    ];
        

array2 = [
{
                "column": "Level",
                "valueOperator": "=",
                "value": "Division"
            } 
            ];
    array3 = [
    {
                "column": "Level",
                "operator": "=",
                "value": "Country"
            }
            ];
            console.log(array1.push(...array2,...array3));

0

For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.

'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


});

Storage.prototype.setObj = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObj = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

After adding JSON object to Array result is (in LocalStorage):

[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]

after this action you can easily send data to server as List in Java

Full code example is here

How do I store a simple cart using localStorage?

Not the answer you're looking for? Browse other questions tagged or ask your own question.