LUA to JSON

For my EPGP plugin: https://github.com/Mottie/epgp

by Mottie

HTML

EPGP addon version: <span id="result">...</span> (from JSON)
<data>
EPGP_DB = {
	["namespaces"] = {
		["log"] = {
			["profiles"] = {
				["Fürsten der Verdammnis"] = {
					["snapshot"] = {
						["time"] = 1363186980,
						["roster_info"] = {
							{
								"Agantica", -- [1]
								"ROGUE", -- [2]
								"09/03-2013", -- [3]
							}, -- [1]
							{
								"Intikamim", -- [1]
								"PALADIN", -- [2]
								"17/02-2013", -- [3]
							}, -- [2]
							{
								"Mondsonde", -- [1]
								"DEATHKNIGHT", -- [2]
								"10/03-2013", -- [3]
							}, -- [23]
						},
						["time"] = 1363016640,
					},
				},
			},
		},
	},
	["global"] = {
		["last_version"] = "5.9.2",
		["last_tier"] = 502,
	},
	["profiles"] = {
		["none"] = {
			["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]
			},
		},
	},
}
</data>

CSS

data {
    display: none;
}
#result {
    color: red;
}

JavaScript

// convert EPGP_DB from LUA to JSON
// remove the ["bonus_loot_log"] block near the bottom to see this work
var str = document.getElementsByTagName('data')[0].innerHTML
    .replace(/\[(.*)\]\s\=\s/g,'$1:')     // 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,'$1')            // remove trailing comma
    .replace(/\}\,\{/g,'],[')             // replace curly bracket set with square brackets
    .replace(/\{\{/g,'[[')                // change double curlies to square brackets
    .replace(/EPGP_DB\s\=/, ''); // remove variable definition

console.log(str);
json = window.JSON.parse(str);
console.log(json);
document.getElementById('result').innerText = json.global.last_version;