To encode an object to JSON in Go, you can use the json.Marshal()
function from the encoding/json
package.
Here's an example of how to encode a struct to JSON:
main.go500 chars29 lines
In this example, we define a struct called Person
with two fields: Name
and Age
. We create a Person
object and then use json.Marshal()
to encode it to JSON. Finally, we convert the JSON bytes to a string and print it to the console.
Output:
26 chars2 lines
gistlibby LogSnag