JSFiddle - React, Tailwind, and code Playground
by agapetos
HTML
<textarea id="code" rows="10">{"username":"agapetos","workers":{"agapetos.main":{"alive":"1","hashrate":"8351","username":"agapetos.main"},"agapetos.main":{"alive":"1","hashrate":"22668","username":"agapetos.main"}}}
</textarea>
<br>
<input type="button" value="parse" onclick="parse()" />
CSS
#code {
font-family: Serif;
font-size: 12pt;
width: 100%;
}
JavaScript
function parse() {
var src = document.getElementById("code").value;
var jsonData = src,
re = /\"(\w+?)(?=\":\{)/g,
names = {},
dups;
jsonData.match(re).forEach(function(v) {
v = v.replace(/\"/, "");
(!names[v]) ? names[v] = 1: names[v]++;
});
dups = Object.keys(names).filter(function(k) {
return names[k] > 1;
}); // getting duplicated keys
dups.forEach(function(k) {
var count = names[k],
i;
names[k] = [];
for (i = 0; i < count; i++) {
names[k].push((i + 1) + "x");
}
});
jsonData = jsonData.replace(re, function(p1) { // replacing duplicate keys
p1 = p1.substr(1);
if (dups.indexOf(p1) !== -1) {
return '"' + names[p1].shift() + p1;
} else {
return '"' + p1;
}
});
console.log(JSON.parse(jsonData));
}