将纯文本数据转换为json

Converting plain text data to json

本文关键字:json 转换 数据 文本      更新时间:2023-09-26

我有一些数据正在尝试用javascript处理。

DATA:
A.         Category one
1.          item one 
2.          item two
B.         Category two
3.          item three
4.          item four
C.         Category three
5.          item five
6.          item six
DESIRED OUTPUT:
[{
"Category one":["item one", "item two"],
"Category two":["item three", "item four"],
"Category three":["item five", "item six"]
}]

有没有一个库可以帮助我用javascript进行文本解析?

THIS IS AS FAR AS I GOT:
function parseFormat(str) {
var arr = [];
str.split(''n').forEach(function (line) {
    var obj = {};
     line.split('.').forEach(function (item) {
        if (isNaN(item)) {
            // ??
        } else {
        }
    });
    return ?;
});
}

帮助?感谢

这是完整的function。请看一下下面的代码。

解析字符串的函数

function parseFormat(strArg) {
  var
    category,
    output = {},  // Output
    str = strArg.trim();  // Remove unwanted space before processing
  str.split(''n').forEach(function(line) {
    var item = line.split('.');
    if (item[0].match(/'d/)) {  // Match a decimal number
        // Remove unwanted space & push
        output[category].push(item[1].trim());
    } else if (item[0].match(/'D/)) {  // Match UPPERCASE alphabet
        // Remove unwanted space
        category = item[1].trim();
        output[category] = []
      }
    });
  return output;
}

输入字符串

// ES6 Template Strings to define multiline string
var str = `
  A.         Category one
  1.          item one
  2.          item two
  B.         Category two
  3.          item three
  4.          item four
  C.         Category three
  5.          item five
  6.          item six
`;

函数调用

// Final output Array
var finalOutput = [];
// Parse input string
var parseStr = parseFormat(str);
finalOutput.push(parseStr);
// Desired JSON output
console.log(JSON.stringify(finalOutput));

您可以在浏览器控制台中查看所需的JSON输出。

希望它能有所帮助!

这是一种将信息从文件格式中提取到一些变量中的简单方法。这不是一个完整的解决方案。尽管一旦你将信息转换为变量,你就可以找到如何json它了。

var category;
var items;
var item = line.split('.'); //Don't use the forEach on the line split.
if (item[0].match(/'d/) ) {
        // match a decimal number
        items = item[1];
    } else if (item[0].match(/'D/) )  {
        //match a letter
        category = item[1];
    }