json - .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 的好方法是什么?
解决方案
从@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, ' ')}`;
推荐阅读
- android - 如何将 Firebase 中的所有数据读入列表视图
- javascript - 如何使用 react 和 django rest 发送文件
- arrays - 如何将数组添加到字典中?
- python - 同时迭代三个不同长度的列表
- r - R中read.xlsx时的日期值不一致
- progressive-web-apps - beforeinstallprompt 仅在 serviceworker 尚未安装时触发
- laravel - 在 Laravel Nova 中按非空值过滤
- java - 如何使用配置文件在 docker 中启动 Spring Boot 应用程序?
- c++ - 在文件中写入和读取对象
- python - 如何将 TXT 文件中的 JSON 数据读入 Pandas