[英]Converting plain text data to json
I have some data that I am trying to process with javascript.我有一些我正在尝试用 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"]
}]
Is there a library that will help me with text parsing in javascript?是否有一个库可以帮助我在 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 ?;
});
}
Help?帮助? Thanks
谢谢
Here is the complete function
.这是完整的
function
。 Please have a look at the code below.请看下面的代码。
Function to parse the string
解析字符串的函数
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; }
Input string
输入字符串
// 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 `;
Function call
函数调用
// Final output Array var finalOutput = []; // Parse input string var parseStr = parseFormat(str); finalOutput.push(parseStr); // Desired JSON output console.log(JSON.stringify(finalOutput));
You can look at the Browser Console for the desired JSON output.您可以查看浏览器控制台以获取所需的 JSON 输出。
Hope it helps!希望能帮助到你!
This is a simple way to get the information out of the file format and into some variables.这是一种从文件格式中获取信息并进入一些变量的简单方法。 It isn't a complete solution.
这不是一个完整的解决方案。 Though once you get the information into variables you can figure out how to json it.
尽管一旦您将信息放入变量中,您就可以弄清楚如何对其进行 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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.