• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

将a.txt的内容,转成b.json的内容

互联网 diligentman 2小时前 2次浏览

  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}


程序员灯塔
转载请注明原文链接:将a.txt的内容,转成b.json的内容
喜欢 (0)