JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,被廣泛應(yīng)用于Web應(yīng)用中。在使用JSON處理數(shù)據(jù)時(shí),我們經(jīng)常需要批量增加數(shù)據(jù)。下面就是一些使用JavaScript對(duì)JSON進(jìn)行批量增加數(shù)據(jù)的示例。
//定義JSON對(duì)象 var jsonStr = '{"name":"Apple", "color":"Red"}'; //將JSON字符串轉(zhuǎn)換成JSON對(duì)象 var jsonObj = JSON.parse(jsonStr); //增加屬性和屬性值 jsonObj.price = "1.5"; //將JSON對(duì)象轉(zhuǎn)換成字符串 var newJsonStr = JSON.stringify(jsonObj); console.log(newJsonStr); //輸出: {"name":"Apple","color":"Red","price":"1.5"} //定義一個(gè)JSON數(shù)組 var jsonArray = [ {"name": "Banana", "color": "Yellow"}, {"name": "Orange", "color": "Orange"}, {"name": "Grape", "color": "Purple"} ]; //增加一個(gè)新的JSON對(duì)象 jsonArray.push({"name": "Watermelon", "color": "Green"}); //輸出增加新的JSON對(duì)象后的數(shù)組 console.log(jsonArray); //輸出: //[ //{"name": "Banana", "color": "Yellow"}, //{"name": "Orange", "color": "Orange"}, //{"name": "Grape", "color": "Purple"}, //{"name": "Watermelon", "color": "Green"} //] //使用循環(huán)批量增加JSON數(shù)據(jù) for (var i = 0; i < 5; i++) { var newObj = { "name": "Fruit"+i, "color": "Green" }; jsonArray.push(newObj); } console.log(jsonArray); //輸出: //[ //{"name": "Banana", "color": "Yellow"}, //{"name": "Orange", "color": "Orange"}, //{"name": "Grape", "color": "Purple"}, //{"name": "Watermelon", "color": "Green"}, //{"name": "Fruit0", "color": "Green"}, //{"name": "Fruit1", "color": "Green"}, //{"name": "Fruit2", "color": "Green"}, //{"name": "Fruit3", "color": "Green"}, //{"name": "Fruit4", "color": "Green"} //]
通過(guò)上述示例,我們可以學(xué)習(xí)到使用JavaScript對(duì)JSON進(jìn)行批量增加數(shù)據(jù)的方法,包括給單個(gè)JSON對(duì)象增加屬性和屬性值、給JSON數(shù)組增加新的JSON對(duì)象和使用循環(huán)批量增加JSON數(shù)據(jù)。這將為我們?cè)赪eb應(yīng)用中操作JSON數(shù)據(jù)提供方便。