博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
golang 将json串转换为树状结构
阅读量:4184 次
发布时间:2019-05-26

本文共 1800 字,大约阅读时间需要 6 分钟。

设计思路:

1. 遇到字符'{'、'[',tabNum++ \n\t*tabNum

2. 遇到字符'"' 必须等待下一个字符'"'出现,形成字符串判断。
3. 遇到字符',' \n\t*tabNum
4. 遇到字符']'、'}' 前面的第一个字符必须插入  tabNum-- \n\t*tabNum
   后面的字符没有','则直接tabNum-- \n\t*tabNum

func 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/

你可能感兴趣的文章
Mysql 表备份 & update的字段来自另一张表
查看>>
深入理解Java类加载器(ClassLoader)
查看>>
虚拟机类加载机制和new对象的过程
查看>>
LeetCode 147. Insertion Sort List插入排序链表的高效简单解法
查看>>
LeetCode 58. Length of Last Word
查看>>
LeetCode Super Pow详解
查看>>
LeetCode 258. Add Digits两种方法
查看>>
基于ID3算法生成决策树
查看>>
【Leetcode】Container With Most Water
查看>>
GDB简明教程
查看>>
Python机器学习库scikit-learn
查看>>
从感知机到人工神经网络
查看>>
计算机视觉与卷积神经网络
查看>>
深入理解支持向量机
查看>>
统计学习方法--决策树
查看>>
Ensemble learning:Bagging,Random Forest,Boosting
查看>>
Scala学习-快速入门
查看>>
Caffe学习-手写数字识别
查看>>
Scala学习-类和对象
查看>>
基于MLlib的机器学习
查看>>