将纯文本数据转换为json
Converting plain text data to json
我有一些数据正在尝试用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];
}
相关文章:
- DOM事件通过JSON转换为java
- 将日期时间从json转换为可读格式
- 如何将JSON转换为HTML下拉菜单
- 将JSON转换为放入Sdcard中的CSV文件
- 将JSON转换为typescript中的字符串数组
- 无法在Angular.js中将JSON转换为数组
- 使用jquery将json转换为数组
- 是否有将基于字符串的JSON转换为Mongoose Schema对象实例的本地功能
- 用D3js将JSON转换为SVG平面图
- 数组json转换为数组json
- 将JSON转换为特定的字符串格式
- 使用AJAX将JSON转换为PHP
- 使用JQuery将JSON转换为数组
- 使用 PHP 将 JSON 转换为 JavaScript
- 将 JavaScript 程序从 JSON 转换为 XML
- 将 JSON 转换为 CSV 格式
- 将 json 转换为 html 表的 JavaScript 不起作用
- 使用 D3 将分层 JSON 转换为 HTML
- 余烬原始 JSON 转换不起作用,但例外
- 如何将JSON转换为角度的HTML