I am currently using gjson's ability to convert a json string into an object. Is this correct? In addition, will gjson provide such capabilities in the future?
package main
import (
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
)
// json -> object
func ParseJsonResult(data *gjson.Result) interface{} {
switch data.Type {
case gjson.Number:
return data.Float()
case gjson.False, gjson.True:
return data.Bool()
case gjson.String:
return data.String()
case gjson.JSON:
if data.IsObject() {
res := make(map[string]interface{}, 0)
err := json.Unmarshal([]byte(data.String()), &res)
if err != nil {
return data.String()
}
return res
} else {
res := make([]interface{}, 0)
err := json.Unmarshal([]byte(data.String()), &res)
if err != nil {
return data.String()
}
return res
}
default:
return data.Raw
}
}
func main() {
myStrTest := `{
"hello1":1,
"hello2":{"haha":3,"haha2":"3","haha3":{"haha4":3}}
}
`
//get hello1
data1 := gjson.Get(myStrTest, "hello1")
if gjson.Valid(data1.String()) {
test1 := ParseJsonResult(&data1)
jsonTest1, err := json.Marshal(test1)
fmt.Println(string(jsonTest1), err)
}
//get hello2
data2 := gjson.Get(myStrTest, "hello2")
if gjson.Valid(data2.String()) {
test2 := ParseJsonResult(&data2)
jsonTest2, err := json.Marshal(test2)
fmt.Println(string(jsonTest2), err)
}
}
I am currently using gjson's ability to convert a json string into an object. Is this correct? In addition, will gjson provide such capabilities in the future?