txt 文本
小王,19
小李,20
小陈,21
成功的JSON样式
{
"list":[
{"name":"小王","age":19},
{"name":"小李","age":20},
{"name":"小陈","age":21}
],
"average":20,
"total":3
}
const fs = require('fs')
fs.readFile('a.txt', 'utf8', function (err, data) {
if (err) {
console.log(err)
return
}
let arr = data.split('\n')
let newArr = []
let sum = 0
let num = 0
arr.forEach(item => {
let obj = {}
obj.name = item.split(',')[0]
obj.age = +item.split(',')[1]
newArr.push(obj)
sum += obj.age
num++
})
let json = {
list: newArr,
average: sum / num,
total: num
}
console.log(json)
fs.writeFile('b.json', JSON.stringify(json), function () {
})
})
成功的JSON样式
{"list":[{"name":"小王","age":19},{"name":"小李","age":20},{"name":"小陈","age":21}],"average":20,"total":3}