In this source code example, we show how to convert JSON to Map with an example.
encoding/json package provides utilities that can be used to convert to and from JSON. The same utility can be used to convert a Golang map to JSON string and vice versa.
Go - Convert JSON to Map - Example 1
We are parsing this JSON string into the below map:
package main
import (
"encoding/json"
"fmt"
)
func main() {
j := `{"1":"Ramesh", "2": "Raj", "3": "Amir"}`
var b map[string]string
json.Unmarshal([]byte(j), &b)
fmt.Println(b)
}
Output:
map[1:Ramesh 2:Raj 3:Amir]
Go - Convert JSON to Map - Example 2
In this example, we will convert JSON to Map type Struct:
package main
import (
"encoding/json"
"fmt"
)
type Employee struct {
FirstName string
LastName string
Email string
}
func main() {
j := `{"1":{"FirstName":"Ramesh", "LastName": "Fadatare", "Email": "ramesh@gmail.com"}}`
var b map[int]Employee
json.Unmarshal([]byte(j), &b)
fmt.Println(b)
}
Output:
map[1:{Ramesh Fadatare ramesh@gmail.com}]