Adding a new array element to a JSON object Ask Question

Adding a new array element to a JSON object Ask Question

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

ファイルに書き戻す前に。新しい要素を追加する良い方法は何ですか? 近づきましたが、すべての二重引用符がエスケープされました。SO で良い答えを探しましたが、このケースを完全にカバーするものはありません。どんな助けでもありがたいです。

ベストアンサー1

翻訳はただの表記; 必要な変更を加えるparseネイティブアプリケーションに変更を適用できるようにJavaScript オブジェクト、 それから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"}]}"

おすすめ記事