没有实际解析的美化工具?

时间:2018-09-13 09:41:31

标签: javascript json formatter

我是JavaScript世界的新手,请耐心等待。

我有一些带有重复键的原始“ JSON”响应,我想使其更具可读性。这里的问题在于嵌入式解析:当我尝试通过JSON.stringify传递信息时-它会将我的输入解析为JSON对象,重复的键消失了。

如何以其他方式解决此问题并保留重复项?

1 个答案:

答案 0 :(得分:2)

是练习Regex解析的超级练习。

让我们逐步看一下我的代码:

// 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";
});

Online Sample