Home >Backend Development >Golang >golang irregular json parsing
json.Unmarshal The operation object is a []byte, which means that all processed JSON must be loaded into memory.
If there is a loaded JSON, it will be faster to use json.Unmarshal. (Recommended learning: go)
json.Decoder operates a stream, or other types that implement the io.Reader interface. Meaning it can be parsed while being received or transmitted. There is no need to re-copy the entire JSON into memory when processing a larger set of data.
The best choice is as follows:
If the data comes from an io.Reader or needs to read data from a stream, choose json.Decoder
If the entire JSON has been loaded into memory, use json.Unmarshal
Indefinite type parsing
Sometimes when encountering JSON with indefinite fields, you need to Judge and analyze at the same time. For example:
t1 := `{"type":"a", id:"aaa"}`t2 := `{"type":"b", id:22222}`
Unmarshal to interface{}
You can first unmarshal to interface{} and then determine the key fields before performing subsequent processing.
type Data struct { Type string `json:"type"` Id interface{} `json:"id"`}func decode(t string) { var x Data err := json.Unmarshal([]byte(t), &x) if err != nil { panic(err) } if x.Type == "a" { fmt.Println(x.Id.(string)) } else { fmt.Println(x.Id.(float64)) //json解析中number默认作为float64解析 } }func main() { t1 := `{"type":"a", "id":"aaa"}` t2 := `{"type":"b", "id":22222}` decode(t1) decode(t2) }
RESULT
aaa 22222
The above is the detailed content of golang irregular json parsing. For more information, please follow other related articles on the PHP Chinese website!