我有一个对象,
var o = {
"comments": " notes" // it first 4 spaces is actually a tab(\t)
}
当我使用 JSON.stringify(o)
对该对象进行字符串化时,它返回 "{"comments":"\t notes"}"
如果我解析该字符串,它会返回原始对象,即 {"comments": "notes"}
但根据我们的要求,我们需要将 JSON.stringify()
结果大写。如果我们执行 JSON.stringify(o).toUpperCase()
,它会为我们提供 "{"COMMENTS":"\T NOTES"}"
有什么方法可以保留 "\t"
或字符串化结果中的空格吗?
最佳答案
您可以尝试使用 for in 循环在键上迭代它,如下所示
var b={};
for(let item in o){
b[item.toUpperCase()]=o[item].toUpperCase();
console.log(b);
}
如果您还想转换嵌套对象,请使用以下函数,它会正常工作。
function changeToUpperCase(obj) {
var newobj = {};
for (let item in obj) {
if (typeof obj[item] == 'object') {
newobj[item.toUpperCase()] = changeToUpperCase(obj[item]);
} else {
newobj[item.toUpperCase()] = obj[item].toUpperCase();
}
}
return newobj
}
关于javascript - JSON 字符串化 : Tabs in objects are converted to\t causing issue while upper casing the result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501455/