Node.js-用于解析的中的json數(shù)據(jù)時(shí),我們可以使用javascript引擎的JSON.parse()函數(shù)。
使用JSON數(shù)據(jù)的信息很少
鍵:值對(duì)是基礎(chǔ)。
{} 包含一個(gè)元素。
[]包含一個(gè)元素?cái)?shù)組。
一個(gè)元素可以有多個(gè)key :value對(duì)。
值可以是簡(jiǎn)單的值,例如數(shù)字或字符串等,也可以是元素或數(shù)組。
數(shù)組中的元素可以使用索引訪問(wèn)
多個(gè)鍵:值對(duì)或元素用逗號(hào)分隔
以下示例可幫助您使用JSON.parse()函數(shù)并從JSON對(duì)象訪問(wèn)元素。
// json數(shù)據(jù) var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}'; // 解析json var jsonParsed = JSON.parse(jsonData); // 訪問(wèn)元素 console.log(jsonParsed.persons[0].name);
運(yùn)行nodejs-parse-json.js的終端輸出
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js John
我們將讀取一個(gè)包含JSON數(shù)據(jù)的File到一個(gè)變量,然后解析該數(shù)據(jù)。
考慮以下JSON文件sample.json
{ "persons": [{ "name": "John", "city": "Kochi", "phone": { "office": "040-528-1258", "home": "9952685471" } }, { "name": "Phil", "city": "Varkazha", "phone": { "office": "040-528-8569", "home": "7955555472" } } ] }
Node.js JSON文件解析程序
// 引入文件系統(tǒng)模塊 var fs = require('fs'); // 讀取文件sample.json文件 fs.readFile('sample.json', // 讀取文件完成時(shí)調(diào)用的回調(diào)函數(shù) function(err, data) { // json數(shù)據(jù) var jsonData = data; // 解析json var jsonParsed = JSON.parse(jsonData); // 訪問(wèn)元素 console.log(jsonParsed.persons[0].name + "'s office phone number is " + jsonParsed.persons[0].phone.office); console.log(jsonParsed.persons[1].name + " is from " + jsonParsed.persons[0].city); });
運(yùn)行上面的Node.js程序。
運(yùn)行nodejs-parse-json-file.js的終端輸出
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json-file.js John's office phone number is 040-528-1258 Phil is from Kochi
在這個(gè)Node.js教程- Node.js JSON文件解析-我們已經(jīng)學(xué)會(huì)了使用JSON.parse()函數(shù),在示例Node.js程序的幫助下從一個(gè)變量或文件解析JSON數(shù)據(jù)。