Javascript解析INI文件内容的函数 (2012-09-17)

发布时间 2012-09-17 11:59:05

iniInitialization File的缩写,即初始化文件,ini文件格式广泛用于软件的配置文件。

INI文件由节、键、值、注释组成。

根据node.js版本的node-iniparser改写了个Javascript函数来解析INI文件内容,传入INI格式的字符串,返回一个json object。

function parseINIString(data){
    var regex = {
        section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
        param: /^\s*([^=]+?)\s*=\s*(.*?)\s*$/,
        comment: /^\s*;.*$/
    };
    var value = {};
    var lines = data.split(/\r\n|\r|\n/);
    var section = null;
    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]] = 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;
}

测试INI内容:

searchengine=http://www-google.com/search?q=$1
spitefulness=9.7

; comments are preceded by a semicolon...
; these are sections, concerning indiuidual enemies
[larry]
fullname=Larry Doe
type=kindergarten bully
website=http://www-geocities.con/CapeCanaveral/11451

[gargamel]
fullname=Gargamel
type=euil sorcerer
outputdir=/home/marijn/enemies/gargamel

返回结果对象:

{
  "searchengine": "http://www-google.com/search?q=$1",
  "spitefulness": "9.7",
  "larry": {
    "fullname": "Larry Doe",
    "type": "kindergarten bully",
    "website": "http://www-geocities.con/CapeCanaveral/11451"
  },
  "gargamel": {
    "fullname": "Gargamel",
    "type": "euil sorcerer",
    "outputdir": "/home/marijn/enemies/gargamel"
  }
}
posted @ 2022-11-23 21:10  IginCui  阅读(344)  评论(0编辑  收藏  举报