在Node.js中,我們經(jīng)常需要訪問和操作JSON數(shù)據(jù)。egg.js提供了非常方便的操作JSON數(shù)據(jù)的方法,本文將介紹egg.js如何獲取JSON節(jié)點(diǎn)。
// 示例數(shù)據(jù) const data = { "name": "Tom", "age": 18, "address": { "city": "Shanghai", "district": "Pudong New Area" }, "hobbies": ["reading", "swimming", "coding"] } // 獲取一級(jí)節(jié)點(diǎn) const name = data.name; // "Tom" const age = data.age; // 18 // 獲取二級(jí)節(jié)點(diǎn) const city = data.address.city; // "Shanghai" const district = data.address.district; // "Pudong New Area" // 獲取數(shù)組節(jié)點(diǎn) const hobbies = data.hobbies; // ["reading", "swimming", "coding"] const firstHobby = data.hobbies[0]; // "reading" const secondHobby = data.hobbies[1]; // "swimming" const thirdHobby = data.hobbies[2]; // "coding"
可以看出,獲取JSON節(jié)點(diǎn)非常簡(jiǎn)單,只需要用“.”訪問節(jié)點(diǎn)即可。如果節(jié)點(diǎn)是數(shù)組,可以使用數(shù)組下標(biāo)訪問。在egg.js中,還提供了更多更靈活的操作JSON數(shù)據(jù)的方法,如JSON字符串轉(zhuǎn)JSON對(duì)象、JSON對(duì)象轉(zhuǎn)字符串等,可根據(jù)實(shí)際需求選擇使用。