156

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.

Charles Wyke-Smith
  • 2,479
  • 3
  • 17
  • 16
  • 7
    `yourObj.theTeam.push({"teamId":"4","status":"pending"});` – PSL Sep 19 '13 at 01: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 Sep 19 '13 at 01:20
  • @brad - I didn't say JSON was an object - I said I had a JSON format object. Thanks for the quick response. – Charles Wyke-Smith Sep 19 '13 at 01:23
  • 3
    @Charles read your title and then reexamine your comment. – Brad Christie Sep 19 '13 at 01: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 Sep 19 '13 at 01:32
  • @brad - yes - conceded! I was going a bit fast - it's important to be accurate! – Charles Wyke-Smith Sep 19 '13 at 19:38

6 Answers6

300

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"}]}"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 23
    +1 for pointing out this needs to be parsed in to an object first to be manipulated. – Brad Christie Sep 19 '13 at 01:21
  • 3
    He said he already has the object in a variable named `teamJSON`. At no point is a string mentioned – Phil Sep 19 '13 at 01:23
  • 9
    @Phil: If it's JSON, it's a string. If it's not, it's not JSON. – user2736012 Sep 19 '13 at 01:25
  • @Phil the question suggests OP wants to go back to a _String_ at the end, where it says `I got close but all the double quotes were escaped` – Paul S. Sep 19 '13 at 01:25
  • 1
    The escaped quotes actually makes me wonder if the JSON was encoded twice. – user2736012 Sep 19 '13 at 01:26
  • 1
    @user2736012 As has been demonstrated, people confuse the term *JSON* with *object literal* all the time. I guess the question needs clarification – Phil Sep 19 '13 at 01:31
  • 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. – Larry Hector Feb 25 '14 at 13:40
  • 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 Feb 12 '20 at 19:18
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.

João Tiago
  • 45
  • 1
  • 6
Ajay Gupta
  • 2,867
  • 23
  • 28
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

Aaron Meese
  • 1,670
  • 3
  • 22
  • 32
Abhijit
  • 242
  • 1
  • 7
  • 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 Feb 12 '20 at 19:18
  • Shafique: Then it's even easier. Just remove the ['theTeam']. portion after obj. So: obj.push(...) – ultrageek Sep 16 '20 at 02: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)

ajitspyd
  • 754
  • 5
  • 8
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));
rahulnikhare
  • 1,362
  • 1
  • 18
  • 25
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?

Community
  • 1
  • 1
Musa
  • 2,596
  • 26
  • 25