向 JSON 对象添加新的数组元素 [英] Adding a new array element to a JSON object

查看:44
本文介绍了向 JSON 对象添加新的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个 JSON 文件中读取了一个 JSON 格式的对象,该文件位于一个名为 teamJSON 的变量中,如下所示:

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

在写回文件之前.添加到新元素的好方法是什么?我接近了,但所有的双引号都被转义了.我已经在 SO 上寻找了一个很好的答案,但没有一个完全涵盖这种情况.任何帮助表示赞赏.

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 只是一个符号;做出你想要的改变 parse 以便您可以将更改应用于本机 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆