首页 > 解决方案 > .dat(未知符号)到 json 格式

问题描述

我正在开发一款名为 Argentum Online 的开源游戏,您可以在此处查看我们的代码https://github.com/ao-libre

我面临的问题是它有很多扩展名为.dat这种格式的文件:

[NPC12] 
Name=Sastre
Desc=¡Hola forastero! Soy el Sastre de Ullathorpe, Bienvenido!
Head=9
Body=50
Heading=3
Movement=1
Attackable=0
Comercia=1
TipoItems=3
Hostil=0
GiveEXP=0
GiveGLD=0
InvReSpawn=0
NpcType=0
Alineacion=0
DEF=0
MaxHit=0
MaxHp=0

[NPC19]
Name=Sastre
Desc=¡Bienvenida Viajera! Tengo hermosas vestimentas para ofrecerte...
Head=70
Body=80
Heading=3
Movement=1
Attackable=0
Comercia=1
TipoItems=3
Hostil=0
GiveEXP=0
GiveGLD=0

我想知道这种解析是否有正确的名称以及将其转换为 json 的好方法是什么?

标签: jsonparsing

解决方案


从@mx0 阅读上面的评论后。该格式称为 INI 格式 https://en.wikipedia.org/wiki/INI_file

这是 INI 到 JSON 之间转换的答案

Npm 模块: https ://github.com/npm/ini

或 ES6 代码段

let ini2Obj = {};
const keyValuePair = kvStr => {
    const kvPair = kvStr.split('=').map( val => val.trim() );
    return { key: kvPair[0], value: kvPair[1] };
};
const result = document.querySelector("#results");
document.querySelector( '#inifile' ).textContent
    .split( /\n/ )                                       // split lines
    .map( line => line.replace( /^\s+|\r/g, "" ) )     // cleanup whitespace
    .forEach( line =>  {                               // convert to object
        line = line.trim();
        if ( line.startsWith('#') || line.startsWith(';') ) { return false; }
        if ( line.length ) {
          if ( /^\[/.test(line) ) {
            this.currentKey = line.replace(/\[|\]/g,'');
            ini2Obj[this.currentKey] = {};
          } else if ( this.currentKey.length ) {
            const kvPair = keyValuePair(line);
            ini2Obj[this.currentKey][kvPair.key] = kvPair.value;
          }
        } 
      }, {currentKey: ''} );

result.textContent += 
    `**Check: ini2Obj['Slave_Settings:11'].ConfigurationfilePath = ${
      ini2Obj['Slave_Settings:11'].ConfigurationfilePath}`;

result.textContent += 
  `\n\n**The converted object (JSON-stringified)\n${
  JSON.stringify(ini2Obj, null, ' ')}`;

原始答案: 用于将 .ini 文件转换为 .json 文件的 Javascript 库(客户端)


推荐阅读