将新数组元素添加到JSON对象 [英] Adding a new array element to a JSON object
问题描述
我有一个JSON格式对象,我从一个名为teamJSON的变量中的JSON文件中读取,如下所示:
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"}
结束
{"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.
推荐答案
JSON 只是一个符号;进行所需的更改 解析
它以便您可以将更改应用于本机 JavaScript对象,然后 stringify
返回 JSON
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"}]}"
这篇关于将新数组元素添加到JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!