如何在 JSON 中清理对象键以转换为 XML



我需要从 JSON 结构中的所有键(和子键(中删除任何斜杠,以便将其转换为 XML,其中斜杠不能出现在标签名称中。

"langServices": {"en/ENGLISH_ONLY": "English"}

我想象一些类似的东西

var finalData = jsonstr.replace("en/", "en-");

,将所有斜杠替换为短划线。所以它也应该适用于这个:{"can/cancel" : "true"},我不知道斜杠之前会出现什么字符串。

var jsonIn = {
"some/other/key/with/slashes": "foo bar baz",
"langServices": {
"en/ENGLISH_ONLY": "English",
"can/cancel": "true"
}
};
function sanitizeKeysRecursively(objIn) {
Object.entries(objIn).forEach(function(kv) {
var sanitizedKey = kv[0].replace(///g, "-");
// call the function recursively on any values that are objects
if (typeof kv[1] === 'object') {
sanitizeKeysRecursively(kv[1]);
}
// set the sanitized key and remove the unsanitized one
if (sanitizedKey != kv[0]) {
objIn[kv[0].replace(///g, "-")] = kv[1];
delete objIn[kv[0]];
}
});
}
sanitizeKeysRecursively(jsonIn);
console.log(jsonIn);

最新更新