tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.39k stars 857 forks source link

How to use gjson's capabilities to convert json strings into objects #334

Closed 15083787153 closed 1 year ago

15083787153 commented 1 year ago

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)
    }
}
15083787153 commented 1 year ago

The Value function meets my needs and the question is closed.