A very good Go-Json parsing library

json is a data format, which is often used for data exchange, page display, serialization and other scenarios. Basically every language has a corresponding json parsing framework. Go language is no exception, and the built-in json library can basically satisfy some Normal development scenarios, but some complex scenarios are not ideal, so it is necessary to find a useful open source json library, first put the address

https://github.com/bitly/go-simplejson

Use of built-in json library

Let's create a structure as follows to test the built-in json library and the open source json library. Let's take a look at how to use it.

//omitempty  这个属性可以在序列化时忽略0值和nil值
// score 不能序列化,属于私有字段
type Student struct {
    Id       int                `json:"id"` //如果想json后的id是字符串可以这样写  `json:"id,string"`
    Name     string             `json:"name"`
    Age      int                `json:"age"`
    score    map[string]float32 `json:"score"`
    Phone    string             `json:"phone,omitempty"`
    Birthday JsonTime           `json:"birthday"`
}

The built-in json library basically has two methods: ToJson and FromJson, which convert an object into a json string and convert a json string into an object. The following two apis, if we want to get a key from the json string , Or when you want to know the type of a certain value, the built-in library does not support at this time, we need to think of other ways

result, err := json.Marshal(v interface{})
err := json.Unmarshal(jsonStr []byte, v interface{})
//序列化
func ToJson(v interface{}) (string, error) {
    result, err := json.Marshal(v)
    if err != nil {
        return "", nil
    }
    return string(result), nil
}
//反序列化
func FromJson(jsonStr []byte, v interface{}) error {
    err := json.Unmarshal(jsonStr, v)
    if err != nil {
        log.Fatalln(err)
        return err
    }
    return nil
}

Use of simple-json

This framework is very simple to use, and the source code is also very concise. There are only three source code files and three test files. Interested students can study the source code implementation. Simple-json is a json parsing library, which means to perform json string analysis. Parsing, serialization and deserialization are not supported by itself.
We construct a json string, and then use simple-json to parse this string according to our scenario to get the result we want

s := `{
        "tagA" : "json string",
        "tagB" : 1024,
        "tagD" : {
            "tagE":1000
        },
        "tagF":[
            "json array",
            1024,
            {"tagH":"json object"}
        ]
}`

First, we obtain a json instance. The framework itself supports multiple methods to obtain a json strength. You can create it directly, or you can directly specify a json string when creating it, or you can create it in the form of a file. Here we use the second method , Which is to use json2 in the above code

json1 := simplejson.New()
json2 := simplejson.NewJson(bs [] byte)
json3 := simplejson.NewFromReader(r io.Reader)

1. In the first scenario, the value of tagA is obtained when the key is obtained. The Get method in the following code returns a Json instance. If you want a specific value, you have to convert it to the type corresponding to the value. Assuming we already know the type of this value, then Get the result directly. String()

tagAValue ,err := json2.Get("tagA").String()

2. In the second scenario, get the value of tagH as the key in the array, first get tagF, return the Json instance, which corresponds to an array, get the Json instance with subscript 2 and then get the key as tagH from this Json instance The value
j,err := json2.Get("tagF").GetIndex(2).Get("tagH").String()
3. In the third scenario, check whether a certain key exists, and the first feedback The value is a json instance, the second returned value is a bool type, true means existence, false means non-existence, if it exists, we can directly convert it to the value type through the json instance

if json, ok := json2.CheckGet("tagD"); ok { //true ,有该字段
    result,_ := json.String()
    fmt.Println(ok, result)
}

4. In the fourth scenario, to get the nested key, simple-json provides a method of searching by path, that is, looking up layer by layer, each layer is a json instance, as follows we get tagE

k, err := json2.GetPath("tagD", "tagE").Int64()

5. There are other scenarios, such as deleting a key, returning to the default value when obtaining the key, etc.

//删除key是tagA值
json2.Del("tagA")
//获取key是tagC的值,如果不存在,一定返回一个默认的字符串,当然也可以返回默认的bool值,int值,等
n := json2.Get("tagC").MustString("default")

Guess you like

Origin blog.csdn.net/weixin_43144260/article/details/113117529