github.com/wangyougui/gf/v2@v2.6.5/encoding/gjson/gjson_z_unit_feature_json_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gjson_test 8 9 import ( 10 "testing" 11 12 "github.com/wangyougui/gf/v2/encoding/gjson" 13 "github.com/wangyougui/gf/v2/frame/g" 14 "github.com/wangyougui/gf/v2/test/gtest" 15 "github.com/wangyougui/gf/v2/text/gstr" 16 ) 17 18 func Test_ToJson(t *testing.T) { 19 type ModifyFieldInfoType struct { 20 Id int64 `json:"id"` 21 New string `json:"new"` 22 } 23 type ModifyFieldInfosType struct { 24 Duration ModifyFieldInfoType `json:"duration"` 25 OMLevel ModifyFieldInfoType `json:"om_level"` 26 } 27 28 type MediaRequestModifyInfo struct { 29 Modify ModifyFieldInfosType `json:"modifyFieldInfos"` 30 Field ModifyFieldInfosType `json:"fieldInfos"` 31 FeedID string `json:"feed_id"` 32 Vid string `json:"id"` 33 } 34 35 gtest.C(t, func(t *gtest.T) { 36 jsonContent := `{"dataSetId":2001,"fieldInfos":{"duration":{"id":80079,"value":"59"},"om_level":{"id":2409,"value":"4"}},"id":"g0936lt1u0f","modifyFieldInfos":{"om_level":{"id":2409,"new":"4","old":""}},"timeStamp":1584599734}` 37 var info MediaRequestModifyInfo 38 err := gjson.DecodeTo(jsonContent, &info) 39 t.AssertNil(err) 40 content := gjson.New(info).MustToJsonString() 41 t.Assert(gstr.Contains(content, `"feed_id":""`), true) 42 t.Assert(gstr.Contains(content, `"fieldInfos":{`), true) 43 t.Assert(gstr.Contains(content, `"id":80079`), true) 44 t.Assert(gstr.Contains(content, `"om_level":{`), true) 45 t.Assert(gstr.Contains(content, `"id":2409,`), true) 46 t.Assert(gstr.Contains(content, `"id":"g0936lt1u0f"`), true) 47 t.Assert(gstr.Contains(content, `"new":"4"`), true) 48 }) 49 } 50 51 func Test_MapAttributeConvert(t *testing.T) { 52 var data = ` 53 { 54 "title": {"l1":"标签1","l2":"标签2"} 55 } 56 ` 57 gtest.C(t, func(t *gtest.T) { 58 j, err := gjson.LoadContent(data) 59 gtest.AssertNil(err) 60 61 tx := struct { 62 Title map[string]interface{} 63 }{} 64 65 err = j.Var().Scan(&tx) 66 gtest.AssertNil(err) 67 t.Assert(tx.Title, g.Map{ 68 "l1": "标签1", "l2": "标签2", 69 }) 70 71 j.Dump() 72 73 var nilJ *gjson.Json = nil 74 nilJ.Dump() 75 }) 76 77 gtest.C(t, func(t *gtest.T) { 78 j, err := gjson.LoadContent(data) 79 gtest.AssertNil(err) 80 81 tx := struct { 82 Title map[string]string 83 }{} 84 85 err = j.Var().Scan(&tx) 86 gtest.AssertNil(err) 87 t.Assert(tx.Title, g.Map{ 88 "l1": "标签1", "l2": "标签2", 89 }) 90 }) 91 }