首页 > 解决方案 > 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"字符串化结果中的空格吗?

标签: javascriptjson

解决方案


您可以尝试使用 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
}

推荐阅读