我有一个从JSON文件读取的JSON格式对象,该对象包含在一个名为teamJSON的变量中,如下所示:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
我想向数组添加一个新项,例如
{"teamId":"4","status":"pending"}
最后
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
在写回文件之前。什么是添加到新元素的好方法?我接近了,但是所有双引号都被转义了。我一直在寻找一个很好的答案,但是没有一个案例能解决这个问题。任何帮助表示赞赏。
JSON 只是一种 表示法 ;进行所需的更改parse,以便可以将更改应用于本机 JavaScript对象 ,然后stringify返回 JSON
parse
stringify
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"}]}"