这是txt文件内容
注:安装nodejs
bulid.js
// 加载File System读写模块 var fs = require('fs'); var os = require('os'); //读取文件 var o = fs.readFileSync('./test.txt','utf-8') //分解txt文件 let arr = o.split(' ') let newArr = arr.filter(function(value,index,arr){ if(value!=''){ return true } return false }) //循环分解数组中的元素 let len = newArr.length let ts = []//诗分组 tsToArr() writeTsToJson() function tsToArr(){ let $ts = [] for(let i=0;i<len;i++){ let str1 = newArr[i].slice(0,3) let str2 = '' //判断下一个是否为标题 if(i+1<len){ str2 = newArr[i+1].slice(0,3) } $ts.push(newArr[i]) if(!isNaN(parseInt(str2))){ ts.push($ts) $ts = [] } } } function writeTsToJson(){ let $len = ts.length let allTs = [] for(let i=0;i<$len;i++){ var tsObj = {} oneTsLen = ts[i].length let content = [] for(let k=0;k<oneTsLen;k++){ if(k==0){ let IDNAMETITLE = ts[i][0].split(':') let str0len = IDNAMETITLE[0].length //id //title let idAndName = IDNAMETITLE[0].split('') let id = '' for(let j =0;j<idAndName.length;j++){ if(j>2){ break } id+=idAndName[j] } let name = '' for(let m =0;m<idAndName.length;m++){ if(m<=2){ continue } name+=idAndName[m] } let title = IDNAMETITLE[1] tsObj.id = id tsObj.author = name tsObj.title = title }else{ content.push(ts[i][k]) } } //content tsObj.content = content allTs.push(tsObj) } var filename = "./test1.json"; fs.writeFileSync(filename, JSON.stringify(allTs)); }
在当前项目路径下使用cmd或者终端
node build.js
搞定