Javascript: Using reviver function, I seem can't get to alter all the keys, while concating the numbers

霸气de小男生 提交于 2019-11-29 16:49:27

The return value of the reviver function only replaces values. If you need to replace keys, then use stringify and replace before the parse call, like this:

JSON.parse(JSON.stringify({"alpha":"zulu"}).replace('"alpha":','"omega":'))

Here is how to replace all numeric keys:

function newkey()
  {
  return Number(Math.random() * 100).toPrecision(2) + RegExp.$1
  }

//Stringify JSON
var foo = JSON.stringify({"123":"ashanga", "12":"bantu"});

//Replace each key with a random number without replacing the ": delimiter
var bar = foo.replace(/\d+("?:)/g, newkey)

//Parse resulting string
var baz = JSON.parse(bar);

Make sure each replaced key is unique, since duplicate keys will be removed by the parse method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!