Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - 向JSON对象添加新的数组元素(Adding a new array element to a JSON object)

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.

(任何帮助表示赞赏。)

  ask by Charles Wyke-Smith translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JSON is just a notation ;

(JSON只是一种表示法 ;)

to make the change you want parse it so you can apply the changes to a native JavaScript Object , then stringify back to JSON

(进行您要parse的更改,以便可以将更改应用于本机JavaScript对象 ,然后重新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"}]}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...