I have some data that I am trying to process with 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?
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
. 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.
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.
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.