[英]Converting plain text file to JSON
So, I've hit a mental break down with the following code, I'm trying to parse a plain text file with the following contents:因此,我对以下代码感到精神崩溃,我正在尝试解析包含以下内容的纯文本文件:
name = rattlesnake
alias = snake,rattle
health = 50
flee = 45
attacks
bite = [3, 8, 30]
punch = [5, 12, 90]
name = bear
alias = bear
health = 100
flee = 15
attacks
claw = [10, 15, 60]
I have the following code that I have written so far, but I hate it and it doesn't do what it's supposed to.到目前为止,我已经编写了以下代码,但我讨厌它并且它没有做它应该做的事情。 I've been trying for hours now.我已经尝试了几个小时了。 Here's the function:这是函数:
var parseModFile = function(contents) {
var hasTab = /(?<=\t).*$/;
var split = contents.split("\r\n");
var pushIt = "{";
var numExtraBraces = 0;
var closeBrace = 0;
for (var l = 0; l < split.length; l++) {
var doIt = "";
if (split[l]) {
if (split[l].length > 1) {
if (hasTab.test(split)) {
doIt = split[l].replace(/\t/g, "");
if (doIt.indexOf(" = ") > -1) {
doIt = doIt.split(" = ");
var key = doIt[0];
var val = doIt[1];
if (key.length > 0 && val.length > 0) {
if (closeBrace == 2) {
doIt = "},\"" + key + "\": \"" + val + "\",";
closeBrace = 0;
} else {
doIt = "\"" + key + "\": \"" + val + "\",";
}
if (closeBrace == 1) {
closeBrace++;
}
}
} else {
doIt = doIt.split(" = ");
var key = doIt[0];
doIt = "\"" + key + "\": {";
numExtraBraces++;
closeBrace = 1;
}
}
}
pushIt += doIt;
}
}
for (var b = 0; b < numExtraBraces; b++) {
pushIt += "}";
}
pushIt += "}";
return pushIt
}
Which is ALMOST correct, but is returning this:这几乎是正确的,但返回的是:
{
"n": "rattlesnake",
"a": "snake,rattle",
"h": "50",
"flee": "45",
"attacks": {
"bite": "[3, 8, 30]",
},
"n": "bear",
"a": "bear",
"h": "100",
"flee": "15",
"attacks": {
"claw": "[10, 15, 60]",
}
}
}
Which obviously isn't quite right, I'd like it to be:这显然不太正确,我希望它是:
{
"n": "rattlesnake",
"a": "snake,rattle",
"h": "50",
"flee": "45",
"attacks": {
"bite": "[3, 8, 30]",
}
},
{
"n": "bear",
"a": "bear",
"h": "100",
"flee": "15",
"attacks": {
"claw": "[10, 15, 60]",
}
}
But I cannot get it to fit at all.但我根本无法让它合身。 What am I missing here?我在这里缺少什么?
Maybe this is not the most elegant solution, but for the purpose you need, it gives a valid JSON output.也许这不是最优雅的解决方案,但为了您需要的目的,它提供了有效的 JSON 输出。
You need to tweak it somewhat, because I used a plain text input with line-breaks.您需要稍微调整一下,因为我使用了带换行符的纯文本输入。
Hope it helps:)希望能帮助到你:)
PS: it needs the [] brackets, because otherwise it is not valid JSON. PS:它需要 [] 括号,否则它不是有效的 JSON。
const fs = require('fs');
fs.readFile('data.txt', 'utf8', function read(err, data) {
if (err) {
throw err;
}
console.log(JSON.stringify(data));
let chunk = data.split("\r\n");
let end = [];
for(let chun of chunk) {
if(chun === "") {end.push("}},{"); continue;}
let it = chun.replace(/\t/g, "").replace(" ", "").replace(/\n/g, "").split(" = ");
switch (it.length) {
case 1:
end.push(`"${it[0]}":{`);
break;
case 2:
end.push(`"${it[0]}":"${it[1]}",`);
break;
}
}
console.log("[{"+end.join("")+"}}]");
});
Output:输出:
[{"name":"rattlesnake","alias":"snake,rattle","health":"50","flee":"45","attacks":{"bite":"[3, 8, 30]","dookie":"[1, 2, 5]",}},{"name":"bear","alias":"bear","health":"100","flee":"15","attacks":{"claw":"[10, 15, 60]","rawr":"[1, 4, 7]",}}]
Here is more compact, easier to read, super customizable regex;这里有更紧凑、更易读、超级可定制的正则表达式;
const content = ` your string `;
let result = ("{\n" + content +"\n }\n}")
.replace(/=\s(\w.+)/g,': "$1"')
.replace(/=/g,':')
.replace(/\]/g,'],')
.replace(/,\n\n/g,'\n }\n},\n{\n')
.replace(/(\w+)\n\s{4}/g,'$1 : { \n ')
.replace(/\"\n/g,'",\n')
.replace(/(\w+)\s:/g,'"$1" :')
.replace(/\],\n\s+\}/g,']\n }');
//making it a valid json by making it an array
result = "[\n" + result + "\n]" ;
Here is a code snippet showing the output;这是一个显示输出的代码片段;
const content = `name = rattlesnake alias = snake,rattle health = 50 flee = 45 attacks bite = [3, 8, 30] punch = [5, 12, 90] name = bear alias = bear health = 100 flee = 15 attacks claw = [10, 15, 60]`; let result = ("{\\n" + content +"\\n }\\n}") .replace(/=\\s(\\w.+)/g,': "$1"') .replace(/=/g,':') .replace(/\\]/g,'],') .replace(/,\\n\\n/g,'\\n }\\n},\\n{\\n') .replace(/(\\w+)\\n\\s{4}/g,'$1 : { \\n ') .replace(/\\"\\n/g,'",\\n') .replace(/(\\w+)\\s:/g,'"$1" :') .replace(/\\],\\n\\s+\\}/g,']\\n }'); //making it a valid json by making it an array result = "[\\n" + result + "\\n]" ; console.log(JSON.parse(result))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.