且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将新数组元素添加到JSON对象

更新时间:2023-01-26 14:23:55

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"}]}"