没有实际解析的美化器?
Beautifier without actual parsing?
我是JavaScript世界的新手,请耐心等待
我收到了一些带有 重复键 的原始 "JSON" 响应,我想让它更具可读性。这里的问题在于嵌入式解析:当我试图通过 JSON.stringify
传递它时 - 它会将我的输入解析为 JSON 对象并且重复键消失。
如何以其他方式解决此问题并保留重复项?
是练习正则表达式解析的超级练习。
让我们逐步查看我的代码:
// Create inline json with nested object.
const originalJson = `{dfkoz:'efzf','dd':"ddd",'zfzfzf','foo': {bar:1}}`;
然后按预期行将其拆分为数组。
const lines = originalJson.replace(/[^,],+/g,"$&\n") \ after each ',' let add '\n' after.
.replace(/{/g,"$&\n") // Add \n after any '{'
.replace(/}/g,"\n$&") // Add \n before any '}'
.split('\n'); // Split string to array with breakline separator
此时你将得到这样的数组:
0: "{"
1: "dfkoz:'efzf',"
2: "'dd':"ddd","
3: "'zfzfzf',"
4: "'foo': {"
5: "bar:1"
6: "}"
7: "}"
然后你必须循环它并添加你的制表符和断行逻辑:
let formatedJson = '';
let nbrOfIndent = 0;
let previousNbrOfIndent = 0;
let isFindIndentMarker = false;
lines.forEach(line => {
previousNbrOfIndent = nbrOfIndent;
// if line is just { or finish by {, we have to increment number of \t for next loop iteration.
if(line === '{' || line.substr(-1) === '{') {
nbrOfIndent++;
isFindIndentMarker = true;
}
// if current line is just } or finish by , we have to decrease number of \t for next tick.
else if(line === '}' || line.substr(-1) !== ',') {
nbrOfIndent--;
isFindIndentMarker = true;
}
formatedJson += "\t".repeat((!isFindIndentMarker)?nbrOfIndent:previousNbrOfIndent) + line + "\n";
});
我是JavaScript世界的新手,请耐心等待
我收到了一些带有 重复键 的原始 "JSON" 响应,我想让它更具可读性。这里的问题在于嵌入式解析:当我试图通过 JSON.stringify
传递它时 - 它会将我的输入解析为 JSON 对象并且重复键消失。
如何以其他方式解决此问题并保留重复项?
是练习正则表达式解析的超级练习。
让我们逐步查看我的代码:
// Create inline json with nested object.
const originalJson = `{dfkoz:'efzf','dd':"ddd",'zfzfzf','foo': {bar:1}}`;
然后按预期行将其拆分为数组。
const lines = originalJson.replace(/[^,],+/g,"$&\n") \ after each ',' let add '\n' after.
.replace(/{/g,"$&\n") // Add \n after any '{'
.replace(/}/g,"\n$&") // Add \n before any '}'
.split('\n'); // Split string to array with breakline separator
此时你将得到这样的数组:
0: "{"
1: "dfkoz:'efzf',"
2: "'dd':"ddd","
3: "'zfzfzf',"
4: "'foo': {"
5: "bar:1"
6: "}"
7: "}"
然后你必须循环它并添加你的制表符和断行逻辑:
let formatedJson = '';
let nbrOfIndent = 0;
let previousNbrOfIndent = 0;
let isFindIndentMarker = false;
lines.forEach(line => {
previousNbrOfIndent = nbrOfIndent;
// if line is just { or finish by {, we have to increment number of \t for next loop iteration.
if(line === '{' || line.substr(-1) === '{') {
nbrOfIndent++;
isFindIndentMarker = true;
}
// if current line is just } or finish by , we have to decrease number of \t for next tick.
else if(line === '}' || line.substr(-1) !== ',') {
nbrOfIndent--;
isFindIndentMarker = true;
}
formatedJson += "\t".repeat((!isFindIndentMarker)?nbrOfIndent:previousNbrOfIndent) + line + "\n";
});