Golang中处理JSON字符串相关
参考文章
jsoniter
注意下里面的 benchmark,基准测试的写法!!!有每种json处理的性能测试!!!
type student struct { Name string Age int } // jsoniter func TestT1(t *testing.T) { // Marshal s1 := student{ Name: "whw", Age: 22, } marshalRet, errMarshal := jsoniter.Marshal(&s1) require.Equal(t, errMarshal, nil) fmt.Printf("marshalRet: %T, %v \n", marshalRet, string(marshalRet)) // marshalRet: []uint8, {"Name":"whw","Age":22} // 直接转为字符串 strRet, errRet := jsoniter.MarshalToString(&s1) require.Equal(t, errRet, nil) fmt.Printf("strRet: %T, %v \n", strRet, strRet) // strRet: string, {"Name":"whw","Age":22} // Unmarshal s2 := new(student) // 得到一个指针 errUnMarshal := jsoniter.Unmarshal(marshalRet, s2) // 记得这里用 指针 接收 require.Equal(t, errUnMarshal, nil) fmt.Printf(">>> %v, %v \n", s2.Name, s2.Age) // 根据字符串解析 s3 := new(student) // 指针 str3 := `{"Name":"sasuke","Age":25}` err3 := jsoniter.UnmarshalFromString(str3, s3) require.Equal(t, err3, nil) fmt.Println("s3: ", s3.Name, s3.Age) // sasuke 25 }
~~~
gjson
https://github.com/tidwall/gjson
func TestT2(t *testing.T) { const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}` last := gjson.Get(json, "name.last") age := gjson.Get(json, "age") fmt.Println("last: ", last) // Prichard fmt.Println("age: ", age) // 47 }
~~~