I've got a JSON object whose keys have dots in their names. I need to replace the dots with 'DOT' (for example).
{
"key1.key": "merciful",
"key2": {
"key2.key": "grateful"
}
}
So, key1.key
converts to key1DOTkey
Using the approach suggested in Change key name in nested JSON structure I used the reviver parameter of JSON.Parse, which works like a charm to replace anything within the key name, except for dots: when replacing dots, it truncates the object.
This code replaces all "e" and works fine
var parseE = JSON.parse(obj, function (k, v) {
if (k.search(".") != -1)
this[k.replace(/e/g, 'DOT')] = v;
else
return v;
});
returns
{
"kDOTy1.kDOTy": "merciful",
"kDOTy2": {
"kDOTy2.kDOTy": "grateful"
}
}
But if I try to replace the dot ".", then the object truncates
var parseDOT = JSON.parse(obj, function (k, v) {
if (k.search(".") != -1)
this[k.replace(/\./g, 'DOT')] = v;
else
return v;
});
returns the first key-value pair, well replaced, but nothing else:
{
"key1DOTkey": "merciful"
}
I have tried using replaceAll
and even creating a function replacing the characters one by one to avoid using regex in case that was the origin. Nothing, same outcome.
Here's a fiddle: https://jsfiddle.net/dpiret/dgk5fp16/7/
Note: replacing all dots from the stringified object won't work for me because it would replace the dots within values as well.
I would much appreciate any indication