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