javascript 将 Lua 数据转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16255770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:55:41  来源:igfitidea点击:

Convert Lua data to JSON

javascriptreplaceluaworld-of-warcraft

提问by Mottie

This EPGP World of Warcraft addonoutputs an epgp.lua database file.

这个EPGP 魔兽世界插件输出一个 epgp.lua 数据库文件。

I wrote a pluginto convert the Lua data into a JSON object for display on a guild website. It was working in older versions of the addon, but now I'm having trouble trying to get it to convert the file properly. Here are two snippets that show the conversion problem - see this demo.

我写了一个插件,把Lua数据转换成JSON对象,在公会网站上展示。它在旧版本的插件中工作,但现在我无法正确转换文件。以下是显示转换问题的两个片段 - 请参阅此演示

The first works great at forming a nested array:

第一个非常适合形成嵌套数组:

["roster_info"] = {
    {
        "Agantica", -- [1]
        "ROGUE", -- [2]
        "09/03-2013", -- [3]
    }, -- [1]
    {
        "Intikamim", -- [1]
        "PALADIN", -- [2]
        "17/02-2013", -- [3]
    }, -- [2]
},

becomes

变成

"roster_info" : [
    [
        "Agantica",
        "ROGUE",
        "09/03-2013"
    ],
    [
        "Intikamim",
        "PALADIN",
        "17/02-2013"
    ]
]

But the string replacment sees this next snippet as a nested array when it should be an object inside of an array:

但是当它应该是数组内的对象时,字符串替换将下一个片段视为嵌套数组:

["bonus_loot_log"] = {
    {
        ["player"] = "Magebox",
        ["timestamp"] = "2013-03-07 13:44:00",
        ["coinsLeft"] = "-1",
        ["reward"] = "|cffa335ee|Hitem:86815:0:0:0:0:0:0:632235520:90:0:445|h[Attenuating Bracers]|h|r",
    }, -- [1]
            {
        ["player"] = "L?utasila",
        ["coinsLeft"] = "-1",
        ["timestamp"] = "2013-03-07 13:47:00",
    }, -- [2]
},

becomes

变成

"bonus_loot_log" : [
    [
        "player" : "Magebox",
        "timestamp" : "2013-03-07 13:44:00",
        "coinsLeft" : "-1",
        "reward" : "|cffa335ee|Hitem:86815:0:0:0:0:0:0:632235520:90:0:445|h[Attenuating Bracers]|h|r"
    ],
    [
        "player": "L?utasila",
        "coinsLeft": "-1",
        "timestamp": "2013-03-07 13:47:00"
    ]
]

Here is the string conversion script that only works on the first snippet.

这是仅适用于第一个片段的字符串转换脚本。

lua_string
    .replace(/\[(.*)\]\s\=\s/g,':')     // change equal to colon & remove outer brackets
    .replace(/[\t\r\n]/g,'')              // remove tabs & returns
    .replace(/\}\,\s--\s\[\d+\]\}/g,']]') // replace sets ending with a comment with square brackets
    .replace(/\,\s--\s\[\d+\]/g,',')      // remove close subgroup and comment
    .replace(/,(\}|\])/g,'')            // remove trailing comma
    .replace(/\}\,\{/g,'],[')             // replace curly bracket set with square brackets
    .replace(/\{\{/g,'[[')                // change double curlies to square brackets
    .replace(/EPGP_DB\s\=/,'');

So, I need some help getting the Lua to convert properly with an array of objects (second example).

所以,我需要一些帮助来让 Lua 正确地转换为一组对象(第二个例子)。

采纳答案by Egor Skriptunoff

// convert EPGP_DB from LUA to JSON
var str = document.getElementsByTagName('data')[0].innerHTML;
var diff;
do {  // replace curlies around arrays with square brackets
    diff = str.length;
    str = str.replace(/\{(((\n\t*)\t)\S.*(.*)*)\,\s--\s\[\d+\]\}/g,'[]');
    diff = diff - str.length;
} while (diff > 0);
str = str
.replace(/EPGP_DB\s=\s/, '')         // remove variable definition
.replace(/\s--\s\[\d+\](\n)/g, '') // remove comment
.replace(/\,(\n\t*\})/g, '')       // remove trailing comma
.replace(/\[(.*?)\]\s\=\s/g,':')   // change equal to colon, remove brackets
.replace(/[\t\r\n]/g,'');            // remove tabs & returns
console.log(str);
json = window.JSON.parse(str);
console.log(json);
document.getElementById('result').innerText = json.global.last_version;

回答by Michal Kottman

You generally cannot convert any Lua table to JSON data simply by using string operations. The problem is that while Lua uses tables for both arrays and dictionaries, JSON needs two different types. There are other syntactical differences.

您通常无法仅使用字符串操作将任何 Lua 表转换为 JSON 数据。问题是 Lua 对数组和字典都使用表,而 JSON 需要两种不同的类型。还有其他语法差异。

This is best solved by a module which converts between Lua and JSON representation. Take a look at the Lua wiki on JSON modulesand find a Lua module to convert Lua to JSON. There are multiple modules, some which are pure Lua, being a good choice to embed into WoW. They correctly detect whether a table represents an array or dictionary and output the relevant JSON.

这最好通过在 Lua 和 JSON 表示之间转换的模块来解决。查看有关 JSON 模块Lua wiki并找到一个 Lua 模块将 Lua 转换为 JSON。有多个模块,其中一些是纯 Lua,是嵌入 WoW 的不错选择。它们正确地检测表是代表数组还是字典并输出相关的 JSON。