向 JSON 对象添加新的数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18884840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a new array element to a JSON object
提问by Charles Wyke-Smith
I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
我从一个 JSON 文件中读取了一个 JSON 格式对象,该文件位于名为 teamJSON 的变量中,如下所示:
{"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.
在写回文件之前。添加到新元素的好方法是什么?我接近了,但所有的双引号都被转义了。我已经在 SO 上寻找了一个很好的答案,但没有一个完全涵盖这种情况。任何帮助表示赞赏。
回答by Paul S.
JSONis just a notation; to make the change you want parseit so you can apply the changes to a native JavaScript Object, then stringifyback to JSON
JSON只是一个符号;进行您想要的更改parse,以便您可以将更改应用于本机JavaScript Object,然后stringify返回到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"}]}"
回答by Ajay Gupta
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last positionthen 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 positionthen 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 positionof 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.
上面的代码块在第二个元素之后添加了一个元素。
回答by Abhijit
First we need to parse the JSON object and then we can add an item.
首先我们需要解析 JSON 对象,然后我们可以添加一个项目。
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.stringifythe objback to JSON
最后,我们JSON.stringify的OBJ回JSON
回答by Ajit A. Kenjale
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.
就我而言,我的 JSON 对象中没有任何现有的数组,因此我必须先创建数组元素,然后再推送该元素。
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)
(此答案可能与此特定问题无关,但可能对其他人有所帮助)
回答by Musa
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
例如,这里有一个类似按钮的元素,用于将项目添加到购物篮以及用于保存在 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):
将 JSON 对象添加到 Array 结果是(在 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"}]
[{"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
执行此操作后,您可以轻松地将数据作为 Java 中的列表发送到服务器
Full code example is here
完整的代码示例在这里

