Javascript 使用regexjs/JQuery将字符串转换为对象
因此,我使用一个程序,将一个可怕的、过时的文本/ascii样式表作为“点击复制”样式输出。我想知道如何使用正则表达式来提取标题和值,然后将它们放入一个对象中。所讨论的字符串与此类似:Javascript 使用regexjs/JQuery将字符串转换为对象,javascript,jquery,regex,json,object,Javascript,Jquery,Regex,Json,Object,因此,我使用一个程序,将一个可怕的、过时的文本/ascii样式表作为“点击复制”样式输出。我想知道如何使用正则表达式来提取标题和值,然后将它们放入一个对象中。所讨论的字符串与此类似: *========================================================================* |Timestamp ||Key1 |Key2 |Key3 |Key4 |Key5 |Key6 | *--------
*========================================================================*
|Timestamp ||Key1 |Key2 |Key3 |Key4 |Key5 |Key6 |
*------------------------------------------------------------------------*
| 01/06/2015 12:00:00 ||0 |12 |47.5 |102 |0 |0 |
*========================================================================*
*========================================================*
|Timestamp ||Key1 |Key2 |Key3 |Key4 |
*--------------------------------------------------------*
| 01/06/2015 12:00:00 ||0.8 |120 |475 |1.2 |
*========================================================
我花了一点时间在上面,最终得到一个键数组,每个表一个值数组,然后在一个数组中,如
[[KeyArray01], [ValueArray01], [KeyArray02], [ValueArray02]]
经过一段时间的纠结,我决定,必须有一个更好的解决方案,我希望有人能有一个例子,说明如何从这个字符串中提取标题和值,并将它们直接放入一个对象中,类似这样:
[{
Timestamp = 01/06/2015 12:00:00
Key1 = 0,
Key2 = 12,
Key3 = 47.5,
Key4 = 102,
Key5 = 0,
Key6 = 0
},{
Timestamp = 01/06/2015 12:00:00
Key1 = 0.8,
Key2 = 120,
Key3 = 475,
Key4 = 1.2
}]
所以我可以简单地浏览一下,在列表或表格中打印出所需的相关数据
我环顾了一下四周,没能想出一个解决方案,任何帮助,或者正确方向上的一点都将不胜感激
问候
裙
更新:对于询问我用于获取阵列的方法的人
function objectify() {
var rawData = codeOutput.getSession().getValue();
b = rawData.match(/\|.*\|/g);
j = [];
for (var i = 0 ; i < b.length; i++) {
j.push(b[i].split("|"))
oid = "";
oval = "";
// Run through each array
// $.each(j,function(i,v) { $.each(v,function(index,value) { console.log(value)});});
} console.log(j)
}
函数objectify(){
var rawData=codeOutput.getSession().getValue();
b=rawData.match(/\\\.\\\\\/g);
j=[];
对于(变量i=0;i
最终更新
好的,所有的答案似乎都与测试数据有关。对我来说最有效的答案是Xotic750。因为它考虑了输出中可能出现的变化,这非常适合我的解决方案
谢谢大家。如果您已经提取了数组,那么最好从这些数组中形成对象 以下是为每个表提取和填充对象的一种方法:
function extract(tabularDataString) {
// Split on double newline (space between tables)
return tabularDataString.split(/\n\n/g).map(function(s) {
var all = [];
var obj = {};
s.split(/\n/g).forEach(function(line) {
var current = [];
// Grab individual values
line.replace(/\| ?([\w\/:. ]+)/g, function($0, v) {
current.push(v.trim());
});
if (current.length) all.push(current);
});
var keys = all[0];
var vals = all[1];
vals.forEach(function(val, i) {
obj[keys[i]] = val;
});
return obj;
});
}
演示:我将采用两步方法,首先获取数组键值(“timestamp”、“key1”等),然后在第二步获取所有值 步骤0 将代码复制到变量中
var str = "you horrible table like string";
步骤1
将字符串拆分为行并提取键值
步骤2
用值填充新数组
这是一把小提琴唯一的问题是你如何得到那根可怕的弦
str='*========================================================================*\n'+
'|Timestamp ||Key1 |Key2 |Key3 |Key4 |Key5 |Key6 |\n'+
'*------------------------------------------------------------------------*\n'+
'| 01/06/2015 12:00:00 ||0 |12 |47.5 |102 |0 |0 |\n'+
'| 02/06/2015 12:00:00 ||1 |14 |45.5 |132 |0 |1 |\n'+
'*========================================================================*\n';
var aStr = str.split('\n');
// get key values
kval = aStr[1].split("|").map(Function.prototype.call, String.prototype.trim).filter(Boolean);
// get values
var fArr=[];
for(var i=3;i<aStr.length;i++) {
if(aStr[i].indexOf('|')>=0) {
tStr = aStr[i].split("|").map(Function.prototype.call, String.prototype.trim).filter(Boolean);
var ttStr = [];
for(var j=0;j<tStr.length;j++) {
ttStr[kval[j]]=tStr[j];
} fArr.push(ttStr);
}
}
console.log(fArr);
str='*==================================================================================================================================*\n'+
“|时间戳| |键1 |键2 |键3 |键4 |键5 |键6 | \n”+
“*-----------------------------------------------------------------------------------------*\n”+
“| 01/06/2015 12:00:00 | 0 | 12 | 47.5 | 102 | 0 | 0 | \n”+
“2015年6月2日12:00:00 | 1 | 14 | 45.5 | 132 | 0 | 1 | \n”+
'*===============================================================================================================================*\n';
var aStr=str.split('\n');
//获取关键值
kval=aStr[1].split(“|”).map(Function.prototype.call,String.prototype.trim).filter(布尔);
//获取价值
var-fArr=[];
对于(变量i=3;i=0){
tStr=aStr[i].split(“|”).map(Function.prototype.call,String.prototype.trim).filter(布尔);
var ttStr=[];
对于(var j=0;j另一种可能的解决方案
功能微调器(列表){
返回列表.map(函数(部分){
返回部分。修剪();
});
}
函数getLines(文本){
返回修剪器(text.split('\n')).filter(函数(部分){
返回部分。字符(0)='|';
});
}
函数getParts(文本){
返回修剪器(text.slice(1,-1).replace('| |','|').split('|');
}
var groups=getLines(document.getElementById('data').textContent).reduce(函数(acc,line){
var last;
if(line.slice(0,10)=='| Timestamp'){
加速推({
标题:getParts(行)
});
}否则{
最后=附件[附件长度-1];
如果(!Array.isArray(last.data)){
last.data=[];
}
last.data.push(getParts(行));
}
返回acc;
},[])。减少(功能(acc,组){
var headers=group.headers;
组数据forEach(函数(基准){
if(datum.length!==headers.length){
抛出新错误(“基准和收割台长度不匹配”);
}
acc.push(标题减少)(功能(记录、标题、索引){
记录[标题]=基准[索引];
返回记录;
}, {}));
});
返回acc;
}, []);
document.getElementById('out').textContent=JSON.stringify(groups,null,2);
*========================================================================*
|时间戳| |键1 |键2 |键3 |键4 |键5 |键6|
*------------------------------------------------------------------------*
| 01/06/2015 12:00:00 ||0 |12 |47.5 |102 |0 |0 |
| 02/06/2015 22:00:00 ||1 |24 |90.5 |204 |1 |1 |
*========================================================================*
*========================================================*
|时间戳| |键1 |键2 |键3 |键4|
*--------------------------------------------------------*
| 01/06/2015 12:00:00 ||0.8 |120 |475 |1.2 |
*========================================================
因为这很有趣,我想我应该提供以下方法:
// getting the element containing the relevant ASCII table
// this is restrictive in that that element must contain
// *only* the ASCII table (for predictable results):
var input = document.getElementById('asciiTable').textContent,
// splitting the input string by new-lines to form an array,
// filtering that array with Array.prototype.filter():
lines = input.split(/\n/).filter(function (line) {
// line is the array-element from the array over
// which we're iterating; here we keep only those
// array elements for which the assessment is true:
return line.indexOf('|') === 0;
}),
// getting the first 'line' of the array, using
// Array.prototype.shift() which contains the headings,
// using shift() also removes that element from the array,
// then we match all occurrences ('g') of a strings
// matching the word-boundary ('\b') followed by one-or-more
// alpha-numerics (\w+) followed by another word-boundary;
// String.prototype.match() returns either null, or an Array
// containing the matched-strings:
keys = lines.shift().match(/\b\w+\b/g),
// initialising an Array:
objArray = [],
// initialising a variable to use within the loop:
values;
// iterating over the lines Array, using
// Array.prototype.forEach():
lines.forEach(function (line, index) {
// the first argument is the array-element,
// the second is the index (the names are user-chosen
// and, so long as they're valid, entirely irrelevant).
// creating an Object to hold the key-value data:
objArray[index] = {};
// using String.prototype.split() on the line, to
// to form an Array; filtering that array (again
// with Array.prototype.filter()):
values = line.split('|').filter(function (value) {
// keeping those array-elements for which
// the trimmed value (removing leading and
// trailing white-space) still has a length
// 0 is falsey, any non-zero value is truthy:
return value.trim().length;
});
// iterating over the keys array, using
// Array.prototype.forEach() (again):
keys.forEach(function (key, i) {
// setting a key on the Object held
// at the index-th index of the array
// (that we created a few lines ago),
// and setting its value to that of
// the trimmed value, found earlier,
// found at the i-th index of the values
// array:
objArray[index][key] = values[i].trim();
});
});
// logging to the console:
console.log(objArray);
// [{"Timestamp":"01/06/2015 12:00:00","Key1":"0","Key2":"12","Key3":"47.5","Key4":"102","Key5":"0","Key6":"0"}]
var input=document.getElementById('asciiTable').textContent,
lines=input.split(/\n/).filter(函数(行){
返回行。indexOf(“|”)==0;
}),
keys=lines.shift().match(/\b\w+\b/g),
objArray=[],
价值观
forEach(函数(行、索引){
objArray[index]={};
values=line.split(“|”).filter(函数(值){
返回值.trim().length;
});
键。forEach(功能(键,i){
objArray[index][key]=值[i].trim();
});
});
C