我有一个textarea用户编辑配置。它的格式如下:解析配置字符串到JavaScript/JSON
foo = 'value'
bar = 2.1
john = false
值可以是false,true,float或strings(无函数)。我需要正则表达这个字符串来创建类似于:
{
foo: 'value',
bar: 2.1,
john: false
}
有没有图书馆或为此?
我有一个textarea用户编辑配置。它的格式如下:解析配置字符串到JavaScript/JSON
foo = 'value'
bar = 2.1
john = false
值可以是false,true,float或strings(无函数)。我需要正则表达这个字符串来创建类似于:
{
foo: 'value',
bar: 2.1,
john: false
}
有没有图书馆或为此?
我把这个answer这应该是你的要求一个良好的开端,并增加了一些进一步的规则来处理不同的数据类型,这也许可以帮助:
var data ="foo = 'value'";
data +="\n" + "bar = 2.1";
data += "\n" + "john = false";
function JSONFY(data){
var regex = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
var value = {};
var lines = data.split(/\r\n|\r|\n/);
var section = null;
function handleSection(sec) {
var isFloat = /^(?:[1-9]\d*|0)?(?:\.\d+)?$/;
if(sec.match(isFloat)) {
return parseFloat(sec);
} else if(sec=='true') {
return true;
} else if(sec=='false') {
return false;
}
return sec.replace(/^['"]/,'').replace(/['"]$/,'');
}
lines.forEach(function(line){
if(regex.comment.test(line)){
return;
}else if(regex.param.test(line)){
var match = line.match(regex.param);
if(section){
value[section][match[1]] = match[2];
}else{
value[match[1]] = handleSection(match[2]);
}
}else if(regex.section.test(line)){
var match = line.match(regex.section);
value[match[1]] = {};
section = match[1];
}else if(line.length == 0 && section){
section = null;
};
});
return value;
}
console.log(JSONFY(data));
这里是fiddle测试。
取决于有多少可以信任的输入数据,你可以写一个简单的功能,利用这样(用jQuery进行简单起见)代码:
var lines = $('textarea').val().split('\n');
var output = '{';
$(lines).each(function(l){
output += '\n\t' + lines[l].replace(/(\w+)\s=\s(.*)/, '$1: $2,');
});
output = output.substring(0, output.length - 1);
output += '\n}';
$('textarea').val(output);
,这里的要点是,你会想要调整正则表达式取决于你想要的严格程度(也就是说,在\s
之后允许空格为?
或者确保这些值是特定格式时可以选择空格。)
好功能在这里发布http://stackoverflow.com/a/12452845/949476 – dfsq 2013-02-15 10:51:40
我用Google搜索了一下,查找了一个小时左右,但我想我可能会在这里得到一些*有用的提示...... – David 2013-02-15 10:52:26