前言
想着做一个JSON美化工具,并且支持处理各种异形格式,例如:
- key没有双引号包裹
- value末尾有多余的逗号
这边的处理主要用到了正则表达式来匹配,并用vue-json-viewer来展示美化后的JSON,框架用的electron + element plus
主要代码
/**
* 修补json
* @param val json
*/
const fixJson = (val: string) => {
// 允许key没有双引号包裹
val = val.replace(/"?[a-zA-Z0-9\-_]+:/g, (match) => {
return `"${match.substring(0, match.length - 1)}":`;
});
// 允许花括号前有一个多余的逗号
val = val.replace(/,[\s\n]*}.*"?/g, (match) => {
if (match.match("\",?")) {
// 不处理字符串
return match;
}
return match.substring(1, match.length);
})
// 允许方括号前有一个多余的逗号
val = val.replace(/,[\s\n]*].*"?/g, (match) => {
if (match.match("\",?")) {
// 不处理字符串
return match;
}
return match.substring(1, match.length);
})
return val;
};
调用代码
// 要格式化的json字符串
const str = '';
// 修补json
const fix = fixJson(str);
// 将json转对象
const obj = JSON.parse(fix);
结果展示
标准JSON
{
"a": 1,
"b": "123",
"c": true
}
key没有双引号包裹
支持包裹与不包裹混用
{
a: 1,
b: "123",
"c": true
}
末尾多余的逗号
{
a: 1,
b: "123,]",
c: true,
d:[1,2,3,],
e:{},
}
复杂情况
{
"a":"1,]",
b:"2,}",
d:{e:{"f":4},},
c:[1,2, {g:true}],
}