This is a creation in Article, where the information may have evolved or changed. Today I would like to share with you some very useful tips for coding and decoding JSON documents. The Go language ' Encoding/json ' package has some interesting features that help us easily parse JSON documents. You can easily convert the JSON in most real-world applications to an interface with a Go-language struct tag or a ' Marshaler ' and ' Unmarshaler ' interface. But one case is tricky: a JSON document that contains escaped JSON elements. as follows: ' json{' id ': 12345, ' name ': ' Test Document ', ' payload ': ' {\ ' message\ ': ' ' hello!\ '} '} ' I don't recommend building an application that creates a document like this, But sometimes the situation is unavoidable, and you want to parse the document in one step, just like normal JSON. Perhaps you start with the following two types: ' ' Gotype logentry struct {ID int ' JSON: ' id ' ' name string ' JSON: ' Name ' ' Payload string ' json: ' Payload ' '}type logpayload struct {message string ' JSON: ' Message ' '} ' ' Matt Holt's [*json-to-go*] (https://mholt.github.io/json-to-go/) To help you build the initial structure from the JSON sample, try it! The first thing to do is to change the ' logentry.payload ' type from ' string ' type to ' logpayload ' type. This is important because this is what you end up trying to get, and that's how the ' Encoding/json ' package handles the element. The problem now is that the actual inbound type of the ' payload ' element is a JSON string. You need to implement the ' Unmarshaler ' interface on the ' Logpayload ' type and decode it as a string, and then decode it to the ' logpayload ' type. "' Gofunc (LP *logpayload) Unmarshaljson (b []byte) error {var s stringif err: = json. Unmarshal (b, &s); Err! = Nil {return ERR}if ERR: = json. Unmarshal ([]byte (s), LP); Err! = Nil {return err} return nil} ' ' looks great, but unfortunately the second ' JSON. Unmarshal ' call will result in recursion of the call stack. You need to decode it into an intermediate type that you can do by defining a new type with a ' logpayload ' base type, such as: ' Gotype fauxlogpayload logpayload ' You can tweak the above code to decode it ' Fauxlogpayload ' type, and then convert the result to ' logpayload ' type. "' Gofunc (LP *logpayload) Unmarshaljson (b []byte) error {var s stringif err: = json. Unmarshal (b, &s); Err! = Nil {return Err}var f fauxlogpayloadif err: = json. Unmarshal ([]byte (s), &f); Err! = Nil {return err} *LP = Logpayload (f) return nil} ' ' Now, it's better to parse the entire document's call site, and also concise: ' ' gofunc main () {doc: = []byte (' {' id ') ' : 12345, "name": "Test Document", "payload": "{\" message\ ": \" Test\ "}"} ') var entry logentryif err: = json. Unmarshal (Doc, &entry); Err! = Nil {fmt. Println ("error!", err)}fmt. Printf ("%v", Entry)} "You can find these codes in [*go playground*] (Https://play.golang.org/p/8l4K4GCF--U). I hope this example illustrates how easily the Go language can separate the focus of ' encoding/decoding ' from business logic. You can use this method at any time to convert the base JSON type to a more complex user-defined type. cheers! Thanks [Redditors Bubux] (HTtps://www.reddit.com/r/golang/comments/801c4i/json_in_go_is_magical/dusgzny/) and [QuiI] (https://www.reddit.com/r/ golang/comments/801c4i/json_in_go_is_magical/duso6pc/), they recommend linking to *json-to-go* and using the Go language string literal in ' main.go ' for my JSON.
via:https://medium.com/@turgon/json-in-go-is-magical-c5b71505a937
Author: Turgon Translator: Sergeychang proofreading: Rxcai
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
902 reads ∙1 likes