From 7530e07e7a3f69b1805d18df0a79674d6d03dcf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 30 Mar 2023 12:26:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E7=AE=80=E7=89=88value?= =?UTF-8?q?=E5=80=BC=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tree/consts.go | 2 ++ tree/generate.go | 50 ++++++++++++++++++++++++++++++++++++++++++- tree/generate_test.go | 2 +- 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/tree/consts.go b/tree/consts.go index 9a34962..2085e53 100644 --- a/tree/consts.go +++ b/tree/consts.go @@ -18,6 +18,8 @@ const ( KeywordArrayEnd = "]" // KeywordColon 冒号 KeywordColon = ":" + // KeywordComma 逗号 + KeywordComma = "," // KeywordDot . KeywordDot = "." // KeywordDoubleQuote 双引号 diff --git a/tree/generate.go b/tree/generate.go index 1d1a99c..0789f99 100644 --- a/tree/generate.go +++ b/tree/generate.go @@ -55,6 +55,7 @@ func (g *Generate) init() error { jsonKey string err error valueType string + jsonValue string ) // 获取类型 @@ -77,7 +78,11 @@ func (g *Generate) init() error { if valueType, startIndex, err = g.getValueType(startIndex); nil != err { return err } - fmt.Println(jsonKey, valueType, startIndex) + // 获取值 + if jsonValue, err = g.getValue(startIndex); nil != err { + return err + } + fmt.Println(jsonKey, valueType, jsonValue, startIndex) } return nil } @@ -217,6 +222,49 @@ func (g *Generate) getValueType(startIndex int) (string, int, error) { return keyValType, startIndex, nil } +// getValue 获取JSON值 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 12:09 2023/3/30 +func (g *Generate) getValue(startIndex int) (string, error) { + valArr := make([]string, 0) + isStart := false + for startIndex < len(g.jsonDataByte) { + str := string(g.jsonDataByte[startIndex]) + if str == KeywordSpace { + startIndex++ + continue + } + if !isStart { + if str == KeywordArrayEnd || str == KeywordObjectEnd || str == KeywordComma { + startIndex++ + continue + } + } + if isStart { + if str == KeywordDoubleQuote || str == KeywordArrayEnd || str == KeywordObjectEnd || str == KeywordComma { + // 值的拼接已结束 + startIndex++ + break + } + } + if str == KeywordDoubleQuote { + if isStart { + startIndex++ + break + } else { + startIndex++ + continue + } + } + isStart = true + valArr = append(valArr, str) + startIndex++ + } + return strings.Join(valArr, ""), nil +} + // isObject 整体是否为对象 // // Author : go_developer@163.com<白茶清欢> diff --git a/tree/generate_test.go b/tree/generate_test.go index c7e118b..a124fa3 100644 --- a/tree/generate_test.go +++ b/tree/generate_test.go @@ -13,7 +13,7 @@ import ( ) func TestNew(t *testing.T) { - jsonData := `{"n\\\\\\ame": "zhang", "age":17}` + jsonData := `{"name": "zhang", "age":17}` g, err := New(jsonData) if nil != err { fmt.Println(err.Error())