Golang JSON Example: Marshal, Unmarshal

Use the encoding/json library to convert Go objects to JSON. Call Marshal and Unmarshal.

JSON. With JSON we have a fast way to store object models as text. Strings, ints—any objects—are supported. And Go provides a built-in encoding library.

With Marshal and Unmarshal, we convert to JSON data and from JSON data. Only one method call is required. Bytes are returned, but we can change these to strings in Go.

Marshal. This example uses the Marshal method. First we have a type Box, which is a custom struct. It has 4 fields—a Width, Height, Color and a bool called Open.
Main: Here we create an instance of our Box type. We specify its Width, Height, Color and its Open value.
Json.Marshal: This receives an object instance. We pass it our Box instance and it converts it to a byte slice of the encoded data.
Result: We convert our bytes (b) to a string and display them with fmt.Println.
Golang program that converts object to JSON encoding package main import ( "encoding/json" "fmt" ) type Box struct { Width int Height int Color string Open bool } func main() { // Create an instance of the Box struct. box := Box{ Width: 10, Height: 20, Color: "blue", Open: false, } // Create JSON from the instance data. // ... Ignore errors. b, _ := json.Marshal(box) // Convert bytes to string. s := string(b) fmt.Println(s) } Output {"Width":10,"Height":20,"Color":"blue","Open":false}

Unmarshal. With json.Unmarshal, we take JSON data (in bytes) and convert it to Go objects. The string keys in the JSON are matched to the field names in the structs.
Text: We specify a JSON string as text. We then convert it to a byte slice with a conversion.
Unmarshal: We invoke Unmarshal by passing a pointer to an empty array of structs. The Languages slice is empty, but Unmarshal populates it.
Finally: We loop over the structs that were created by Unmarshal(). We display their Id and Name fields.
Golang program that uses json.Unmarshal package main import ( "encoding/json" "fmt" ) type Language struct { Id int Name string } func main() { // String contains two JSON rows. text := "[{\"Id\": 100, \"Name\": \"Go\"}, {\"Id\": 200, \"Name\": \"Java\"}]" // Get byte slice from string. bytes := []byte(text) // Unmarshal string into structs. var languages []Language json.Unmarshal(bytes, &languages) // Loop over structs and display them. for l := range languages { fmt.Printf("Id = %v, Name = %v", languages[l].Id, languages[l].Name) fmt.Println() } } Output Id = 100, Name = Go Id = 200, Name = Java

Int array. In JSON we can have arrays that contain values (like 100, 200, 300). These are labeled with a key (like Positions). Here we handle an int array and get an int slice from it.
Result: This struct contains an int slice with field name Positions. This where the int array values are placed.
Unmarshal: We use this to convert our byte array of JSON data into a single struct. Finally we print values on the Result struct.
Golang program that handles int array in JSON package main import ( "encoding/json" "fmt" ) type Result struct { Positions []int } func main() { // This JSON contains an int array. text := "{\"Positions\": [100, 200, 300, -1]}" // Get bytes. bytes := []byte(text) // Unmarshal JSON to Result struct. var result Result json.Unmarshal(bytes, &result) // Our int array is filled. fmt.Printf("Positions = %v", result.Positions) fmt.Println() // Print int array length. fmt.Printf("Length = %v", len(result.Positions)) fmt.Println() } Output Positions = [100 200 300 -1] Length = 4

A review. With Marshal and Unmarshal we convert Go object so JSON and back again. The encoding/json package is powerful. It enables robust support for this lightweight format.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.