Converting Plain Text Data To Json
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 thre
Solution 1:
Here is the complete function
. Please have a look at the code below.
Function to parse the string
functionparseFormat(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()); } elseif (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 Arrayvar finalOutput = []; // Parse input stringvar parseStr = parseFormat(str); finalOutput.push(parseStr); // Desired JSON outputconsole.log(JSON.stringify(finalOutput));
You can look at the Browser Console for the desired JSON output.
Hope it helps!
Solution 2:
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];
} elseif (item[0].match(/\D/) ) {
//match a letter
category = item[1];
}
Post a Comment for "Converting Plain Text Data To Json"