codepen demo : codepen.io/vaynevayne/…
const input = {
"days7": "总计",
"total_row": true,
"pivot": {
" ": {
"days7": "总计",
"install": 1252968,
"os_name": " ",
"total_row": true,
"c":{
name:"zzz",
}
}
}
}
const output = "{
'days7': '总计',
'total_row': true,
'pivot': {
' ': {
'days7': '总计',
'install': 1252968, // 安装
'os_name': ' ', // 系统
'total_row': true,
'c': {
'name': 'zzz', // 姓名
}
}
}
}"
源码
function replacer(key, value) {
// Filtering out properties
if (typeof value !== "object") {
return `{{${value}}},` + (commnetMap[key] ? " // " + commnetMap[key] : "");
} else {
return value;
}
}
const replacer2 = (match, p1) => {
if (/^\d+$/.test(p1) || ["true", "false", "null", "undefined"].includes(p1)) {
return p1;
} else {
return `"${p1}"`;
}
};
const withComment = (obj) => {
return JSON.stringify(obj, replacer, "\t")
.replaceAll(/"\{\{(.*)\}\}/g, replacer2)
.replaceAll(/(?<=\/\/[^"]*)(",?)/g, "")
.replaceAll(/(,",|,")/g, ",");
};
withComment(data? data :{});