a.txt内容
小王,19
小李,20
小陈,21
b.json内容
{
"list":[
{"name":"小王","age":19},
{"name":"小李","age":20},
{"name":"小陈","age":21}
],
"average":20,
"total":3
}
js 整理数据
// 整理数据,将a.txt的内容,转成b.json的内容。 const fs = require('fs') const path = require('path') let list = [] // 获取a 的内容 fs.readFile(path.join(__dirname,'a.txt'), 'utf8', (err, data) => { if (err) { console.log('错误', err) return } //console.log(data)//小王,19小李,20小陈,21 //把data转换成数组 let arr = data.split('\r\n') //console.log(arr)//[ '小王,19', '小李,20', '小陈,21' ] let newArr=[] arr.forEach(item => { newArr.push(item.split(',')) }) // console.log(newArr)//[ [ '小王', '19' ], [ '小李', '20' ], [ '小陈', '21' ] ] let sumAge=0 let obj={} for (let i = 0; i < arr.length; i++){ obj = { name: newArr[i][0], age:newArr[i][1] } sumAge += +newArr[i][1] list.push(obj) } let average=sumAge/list.length //console.log(list) // [ // { name: '小王', age: '19' }, // { name: '小李', age: '20' }, // { name: '小陈', age: '21' } // ] let resObj = { list: list, average:average, total:list.length } console.log(resObj) // 写入b.json中 fs.writeFile(path.join(__dirname, 'b.json'),JSON.stringify(resObj), (err) => { console.log('错误', err) }) })