json
[
{
"name": "小王"
},
{
"name": "小李"
},
{
"name": "小张"
}
]
yourfile.js
const fs = require('fs');
// console.log(fs)
fs.writeFile('json.json', 'utf8', (err) => {
console.log('err', err);
})
const obj = [{ "name": "小王" }, { "name": "小李" }, { "name": "小张" }]
const str = JSON.stringify(obj)
fs.writeFile('json.json', str, 'utf8', (err) => {
// console.log('err', err);
console.log(err);
})
作业二
a.txt
小王,19
小李,20
小陈,21
a.js
const fs = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname, 'a.txt'), 'utf8', (err, data) => {
if (err) {
console.log('err是', err);
} else {
// console.log(data);
const arr = data.split('\r\n')
//console.log(arr);
// console.log(arr[0]);
// console.log(arr.length);
let list = []
let sum = 0
let avg;
let bigobj = {}
arr.forEach(item => {
//console.log(item);
let arr1 = item.split(',')
//console.log(arr1);
let obj = {};
obj.name = arr1[0].substr(0, 2)
obj.age = arr1[1].substr(0, 2)
// console.log(obj);
list.push(obj)
//强制类型转换
sum += parseInt(obj.age)
});
//console.log(list);
avg = sum / list.length;
console.log(avg);
bigobj.list = list;
bigobj.average = avg;
bigobj.total = arr.length
fs.writeFile(path.join(__dirname, 'b.json'), JSON.stringify(bigobj), (err) => {
console.log('err', err);
})
}
})
b.json
{
"list": [
{
"name": "小王",
"age": "19"
},
{
"name": "小李",
"age": "20"
},
{
"name": "小陈",
"age": "21"
}
],
"average": 20,
"total": 3
}