如何使用JSON Stringify替换所有键和值?

时间:2017-11-06 19:57:26

标签: javascript json node.js recursion

我正在研究利用JavaScript中的JSON.Stringify中的replacer函数参数来改变word-case(toUpper / toLower case),问题是我的JSON不是直键:value ,一些值也是键,它们本身也有值,所以我需要遍历所有键和值,检查值是否也是一个键,并确保我更改所有键和值的大小写(toUpper或toLower)。 我知道JSON.Stringify(object,ReplacerFunction)中的replacer函数遍历所有键和值并在内部进行修改然后返回键和值,但是虽然我已经阅读了这个,但是我无法应用它,我不确定我是否应该在更换器功能中应用递归或如何,感谢任何帮助。

我的代码:

 function _replacer(name,val){
   if(typeof val != "object"){
       return val.toString().toUpperCase()
   }
   if(typeof name != "object"){
            return name.toString().toUpperCase()
        }

   console.log("key = "+name+" type: "+typeof  name);
   console.log("value ="+val+" type: "+typeof  val);

    }

此外:

 function _replacer(name,val){
   if(typeof val != "object" &&typeof  val ==="string"){
       return val=val.toUpperCase()
   }
   if(typeof name != "object" &&typeof  name ==="string"){
            name=name.toUpperCase()
        }
    return val;
    }

此外,我最终进入了这个阶段:

 var res = JSON.parse(JSON.stringify(j, function(key, value) {
        return typeof value === "string" ? value.toUpperCase() : value
    }));

但是此代码仅将非常低级别的值大写,而不是所有键/值,原因是因为我只能从replacer函数返回一个值,在这种情况下是值。

1 个答案:

答案 0 :(得分:0)

replacer中的JSON.stringify功能,不允许您将密钥替换为documented in MDN。它允许您转换值,或完全省略键/值对(通过返回undefined)。

你最好的选择可能是在对象进行字符串化之前对其进行转换。 Underscore或Lodash会让这很简单,但你可以在没有太多麻烦的情况下本地做到这一点:

const xform = obj => {
  return Object.keys(obj).reduce((xformed, key) => {
    let value = obj[key]

    if (typeof value ==='string') value = value.toUpperCase()
    else if (typeof value === 'object') value = xform(value)

    xformed[key.toUpperCase()] = value
    return xformed
  }, {})
}

console.log(JSON.stringify(xform({a: 'b', c: 1, d: {e: 'f'}})))
// {"A":"B","C":1,"D":{"E":"F"}}

如果您愿意,可以在之后使用RegEx和replace 进行字符串化。代码当然更短,但可能性更低:

const stringified = JSON.stringify({a: 'b', c: 1, d: {e: 'f'}})
console.log(stringified.replace(/".+?"/g, s => s.toUpperCase()))
// {"A":"B","C":1,"D":{"E":"F"}}