本文共 1800 字,大约阅读时间需要 6 分钟。
设计思路:
1. 遇到字符'{'、'[',tabNum++ \n\t*tabNum
2. 遇到字符'"' 必须等待下一个字符'"'出现,形成字符串判断。 3. 遇到字符',' \n\t*tabNum 4. 遇到字符']'、'}' 前面的第一个字符必须插入 tabNum-- \n\t*tabNum 后面的字符没有','则直接tabNum-- \n\t*tabNumfunc TraverseJsonToTree(json []byte) []byte { stringFlag := false jsonTree := make([]byte, 0) tabNum := 0 dirFlag := false jsonLen := len(json) for i, jsChar := range json { if stringFlag { jsonTree = append(jsonTree, jsChar) if jsChar == '"' { stringFlag = false } continue } if jsChar == '"' { jsonTree = append(jsonTree, jsChar) stringFlag = true continue } if jsChar == '{' || jsChar == '[' { jsonTree = append(jsonTree, jsChar) jsonTree = append(jsonTree, '\r') jsonTree = append(jsonTree, '\n') tabNum++ for tabIndex := 0; tabIndex < tabNum; tabIndex++ { jsonTree = append(jsonTree, '\t') } continue } if jsChar == ',' { jsonTree = append(jsonTree, jsChar) jsonTree = append(jsonTree, '\r') jsonTree = append(jsonTree, '\n') for tabIndex := 0; tabIndex < tabNum; tabIndex++ { jsonTree = append(jsonTree, '\t') } continue } if dirFlag { dirFlag = false tabNum-- jsonTree = append(jsonTree, '\r') jsonTree = append(jsonTree, '\n') for tabIndex := 0; tabIndex < tabNum; tabIndex++ { jsonTree = append(jsonTree, '\t') } jsonTree = append(jsonTree, jsChar) continue } if jsChar == ']' || jsChar == '}' { tabNum-- jsonTree = append(jsonTree, '\r') jsonTree = append(jsonTree, '\n') for tabIndex := 0; tabIndex < tabNum; tabIndex++ { jsonTree = append(jsonTree, '\t') } jsonTree = append(jsonTree, jsChar) if (i + 1) < jsonLen { if json[i+1] != ',' { dirFlag = true } } continue } if jsChar == ':' || (jsChar >= '0' && jsChar <= '9') { jsonTree = append(jsonTree, jsChar) continue } } return jsonTree}
转载地址:http://dauoi.baihongyu.com/