txt数据转换成json数据保存

txt数据

小王,19
小李,20
小陈,21

js代码

//初始化
const fs = require('fs');
const path = require('path')
//读取txt文档的数据
fs.readFile(path.join(__dirname, './a.txt'), 'utf8', function (err,data) {
    if (err) {
        console.log(err);
        return
    }
    //转化成数组
    let arr = data.split('\n')
    //遍历数组
    let list = []
    let sum = 0
    arr.forEach(item => {
        let start = item.substring(0,2)
        let end =item.substring(3)
        str = `{"name":"${start}","age":${end}}`
        list.push(str)    
        sum += Number(end)
    })
    let total = list.length
    let average = sum / total
   
    //整合json数据
    let re = `
    {"list":[${list}],"average":${average},"total":${total} }
    `
    fs.writeFile(path.join(__dirname, './b.json'), re, 'utf8', function (err) {
        if (err) {
            console.log(err);
            return
        }
        console.log('写入成功');
    })
    
})

成功后的json数据


    {"list":[{"name":"小王","age":19
},{"name":"小李","age":20
},{"name":"小陈","age":21}],"average":20,"total":3 }

上一篇:c++primer string::size_type


下一篇:C++ primer第六章—函数