2013-02-15 131 views
0

我有一個textarea用戶編輯配置。它的格式如下:解析配置字符串到JavaScript/JSON

foo = 'value' 
bar = 2.1 
john = false 

值可以是false,true,float或strings(無函數)。我需要正則表達這個字符串來創建類似於:

{ 
    foo: 'value', 
    bar: 2.1, 
    john: false 
} 

有沒有圖書館或爲此?

+1

好功能在這裏發佈http://stackoverflow.com/a/12452845/949476 – dfsq 2013-02-15 10:51:40

+0

我用Google搜索了一下,查找了一個小時左右,但我想我可能會在這裏得到一些*有用的提示...... – David 2013-02-15 10:52:26

回答

0

我把這個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測試。

0

取決於有多少可以信任的輸入數據,你可以寫一個簡單的功能,利用這樣(用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之後允許空格爲?或者確保這些值是特定格式時可以選擇空格。)