This is a creation in Article, where the information may have evolved or changed.
Rawmessage type
There is such a type in the Encoding/json library:
The Rawmessage type is a JSON object that retains its original encoding. This type implements the marshaler and Unmarshaler interfaces for delaying the decoding of JSON or the encoding of precomputed JSON.
In actual work, we may encounter JSON data of this type:
Package Mainimport "Encoding/json"//Jsontext comes from http://json.org/example.htmlvar jsontext = []byte (' {' glossary ') : {"title": "Example Glossary", "Glossdiv": {"title": "S", "glosslist": {"Glossentry": { "ID": "SGML", "Sortas": "SGML", "glossterm": "Standard generalized Markup Language "," acronym ":" SGML "," abbrev ":" ISO 8879:1986 "," Glossdef ": {" pa RA ":" A meta-markup language, used to create markup languages such as DocBook. "," glossseealso ": [ "GML", "XML"}, "Glosssee": "Markup" }}}}} ') type glossary struct {glossary struct {title string ' JSON: ' title ' ' glossdiv struct {title String ' JSON: ' title ' ' glosslist struct {glossentry struct {id string ' JSON: ' id ' ' Sortas string ' json: ' Sortas ' ' G Lossterm string ' JSON: ' GLossterm "' Acronym string ' JSON:" acronym "' Abbrev string ' JSON:" abbrev "' glossdef struct {Para string ' JSON:" Para "' Glossseealso []string ' JSON:" Glossseealso "'} ' JSON:" Glossdef "' Glosssee string ' JSON:" Glosssee "'} ' JSON:" Glossentry "'} ' JSON:" Glosslist "'} ' JSON:" Glossdiv "'} ' JSON:" Glossary "'}func Main () {var g glossaryjson. Unmarshal (Jsontext, &g)}
Write a half-day structure type, but only use the outermost Title and glossdiv.title, then how can we do this situation appropriate?
package mainimport "encoding/json"// jsonText comes from http://json.org/example.htmlvar jsonText = []byte(`{ ... // 此处省略, 同上}`)type glossarySectional struct {Glossary struct {Title string `json:"title"`GlossDiv struct {Title string `json:"title"`GlossList json.RawMessage `json:"GlossList"` // diff: delay JSON decoding} `json:"GlossDiv"`} `json:"glossary"`}func main() {var g glossarySectionaljson.Unmarshal(jsonText, &g)}
At a glance, Rawmessage plays the role of delaying decoding a JSON value.
Conclusion:
For some of the performance-related JSON parsing, we can use JSON. Rawmessage to improve performance.