forked from kiss5891/NodeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.js
More file actions
47 lines (43 loc) · 1.55 KB
/
JSON.js
File metadata and controls
47 lines (43 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
使用fs模組讀取json檔案
*/
var fs = require('fs'); //導入Filesysten模組
fs.readFile('0.1_example.json','utf8',function(err,data){ //讀取0.example.json檔案中內容放進data
if(err){
throw err; //拋出錯誤
}
console.log(data); //秀出讀取的資料內容
console.log(JSON.parse(data)); //秀出將文字轉為json的檔案內容
console.log(JSON.parse(data)["string"]); //秀出json中key為string的value
console.log(JSON.parse(data)["number"]); //秀出json中key為number的value
console.log(JSON.parse(data)["information"]); //秀出json中key為information的value
console.log(JSON.parse(data)["information"]["name"]); //秀出json中key為information.name的value
console.log(JSON.parse(data)["information"]["tel"][0]); //秀出json中key為information.tel[0]的value
fs.writeFile('0.2_example.json',JSON.stringify(JSON.parse(data)),function(err){ //將物件轉換為文字後寫入檔案
if(err){
throw err;
}
console.log('Saved'); //寫入成功後顯示Saved
});
});
//------------------------------
/*執行結果
{
"string" : "Linux",
"number" : 1234,
"information":{
"name" : "Alex",
"age" : 22,
"tel" :["0987654321","0412345678"]
}
}
{ string: 'Linux',
number: 1234,
information: { name: 'Alex', age: 22, tel: [ '0987654321', '0412345678' ] } }
Linux
1234
{ name: 'Alex', age: 22, tel: [ '0987654321', '0412345678' ] }
Alex
0987654321
Saved
*/