Charles Wyke-Smith Charles Wyke-Smith - 6 months ago 10
Javascript Question

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:

{"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.

Answer

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