javascript JSON.parse 下画线转驼峰
原数据
let str='{"a_b":2,"a_c":{"a_b_c":1,"b_c":2},"ad":[{"a_b_c_d":4,"a_b_c":3,"a_c":{"a_b_c":3,"b_c":2}},{"a_e":{"a_B_c_D_e":5,"abcde":5,"ac_bd":4}}]}';
直接转换为JSON
console.log(JSON.stringify(JSON.parse(str),null,2));
/**
{
"a_b": 2,
"a_c": {
"a_b_c": 1,
"b_c": 2
},
"ad": [
{
"a_b_c_d": 4,
"a_b_c": 3,
"a_c": {
"a_b_c": 3,
"b_c": 2
}
},
{
"a_e": {
"a_B_c_D_e": 5,
"abcde": 5,
"ac_bd": 4
}
}
]
}
**/
使用reviver进行下画线转驼峰后
//转换方法
function toHump(k,v) {
if(v instanceof Array){
return v;
}
if(v instanceof Object) {
let res = {};
for(let key in v){
let parts = key.split('_');
let newKey = "";
for(let k of parts){
if(newKey === ""){
newKey = k;
}else{
newKey += k[0].toUpperCase()+k.substr(1);
}
}
res[newKey] = v[key];
}
return res;
}
return v;
}
console.log(JSON.stringify(JSON.parse(str,toHump),null,2));
/**
{
"aB": 2,
"aC": {
"aBC": 1,
"bC": 2
},
"ad": [
{
"aBCD": 4,
"aBC": 3,
"aC": {
"aBC": 3,
"bC": 2
}
},
{
"aE": {
"aBCDE": 5,
"abcde": 5,
"acBd": 4
}
}
]
}
**/