javascript - JSON Stringify:对象中的制表符转换为 \t 导致问题,而大写结果
问题描述
我有一个对象,
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
}
推荐阅读
- python - 使用 tkinter 按钮更改没有函数的变量的值
- ruby-on-rails - Rspec 引发错误未按预期工作,需要正确的语法
- laravel - 如何从 Laravel Eloquent ModelObserver 强制更新而不是允许它创建新记录
- node.js - “路径”参数必须是字符串类型。接收到的类型未定义 - Ionic 4 - 仅限 Windows
- android - 我可以在 DialogFragment.dismiss() 之后做一些工作吗
- c++ - 我正在尝试使用简单的堆栈推送和弹出来反转字符串。但是我收到一些我无法理解的错误
- javascript - 将数据从反应传递到节点服务器
- c# - 我应该如何验证 DTO?
- caching - 具有类似于竞态条件的计时器悖论的缓存
- python - 是否有在 python selenium webdriver 中截屏以及系统时间戳的解决方案?