3 回答
![?](http://img1.sycdn.imooc.com/545868550001f60202200220-100-100.jpg)
TA贡献1802条经验 获得超5个赞
您可以手动执行以使其成为有效的 JSON,然后对其进行解析:
const luaStr = `{
["glow"] = true,
["xOffset"] = -287.99981689453,
["yOffset"] = -227.55575561523,
["anchorPoint"] = "CENTER",
["cooldownSwipe"] = true,
["customTextUpdate"] = "update",
["cooldownEdge"] = false,
["icon"] = true,
["useglowColor"] = false,
["internalVersion"] = 24,
["keepAspectRatio"] = false,
["animation"] = {
["start"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
["main"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
["finish"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
}}`;
const result = luaStr
.replace(/\[|\]/g, '') // remove the brackets
.replace(/=/g, ':') // replace the = with :
.replace(/(\,)(?=\s*})/g, ''); // remove trailing commas
const parsed = JSON.parse(result);
console.log(result);
![?](http://img1.sycdn.imooc.com/533e50ed0001cc5b02000200-100-100.jpg)
TA贡献1858条经验 获得超8个赞
这只是部分解决方案。在某些情况下,如果字符串中的文本与关键语法匹配,它可能会失败。但这可能不是你关心的问题。
const lua = `
{
["glow"] = true,
["xOffset"] = -287.99981689453,
["yOffset"] = -227.55575561523,
["anchorPoint"] = "CENTER",
["cooldownSwipe"] = true,
["customTextUpdate"] = "update",
["cooldownEdge"] = false,
["icon"] = true,
["useglowColor"] = false,
["internalVersion"] = 24,
["keepAspectRatio"] = false,
["animation"] = {
["start"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
["main"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
["finish"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
}
}`
const lua2json = lua =>
JSON .parse (lua .replace (
/\[([^\[\]]+)\]\s*=/g,
(s, k) => `${k} :`
)
.replace (/,(\s*)\}/gm, (s, k) => `${k}}`))
console .log (
lua2json (lua)
)
我不知道您是要创建 JSON 还是对象。我选择了后者,但您可以随时取下JSON.parse包装纸。
![?](http://img1.sycdn.imooc.com/5458620000018a2602200220-100-100.jpg)
TA贡献1744条经验 获得超4个赞
这里有一些你可能不知道的东西,它{ ["someString"]: 2 }是有效的 javascript,并将评估{someString: 2}哪个是有效的 json。唯一的问题是它需要评估,这意味着使用eval(如果可以避免的话,你真的不应该这样做)。
const luaStr = `{
["glow"] = true,
["xOffset"] = -287.99981689453,
["yOffset"] = -227.55575561523,
["anchorPoint"] = "CENTER",
["cooldownSwipe"] = true,
["customTextUpdate"] = "update",
["cooldownEdge"] = false,
["icon"] = true,
["useglowColor"] = false,
["internalVersion"] = 24,
["keepAspectRatio"] = false,
["animation"] = {
["start"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
["main"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
["finish"] = {
["duration_type"] = "seconds",
["type"] = "none",
},
}}`;
const jsonString = luaStr.replace(/\] = /g, ']: ');
const jsonObj = eval(`(${jsonString})`);
console.log(jsonObj);
添加回答
举报