Go Program to Convert JSON to Struct
json.Unmarshal([]byte(jsonData), &yourStruct) to convert JSON string jsonData into a Go struct yourStruct.Examples
How to Think About It
json.Unmarshal to parse the JSON string into an instance of that struct. This automatically fills the struct fields with the JSON data.Algorithm
Code
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { jsonData := `{"Name":"Alice","Age":30}` var p Person err := json.Unmarshal([]byte(jsonData), &p) if err != nil { fmt.Println("Error:", err) return } fmt.Println(p) }
Dry Run
Let's trace converting JSON '{"Name":"Alice","Age":30}' to struct Person.
Define struct Person
Person has fields Name (string), Age (int).
Call json.Unmarshal
json.Unmarshal parses JSON bytes and fills struct fields.
Struct after Unmarshal
Person{Name: "Alice", Age: 30}
| Step | Action | Value |
|---|---|---|
| 1 | Define struct | Person{Name string, Age int} |
| 2 | Unmarshal JSON | {"Name":"Alice","Age":30} |
| 3 | Resulting struct | {Name: "Alice", Age: 30} |
Why This Works
Step 1: Struct matches JSON keys
The struct fields must have names matching JSON keys for json.Unmarshal to fill them correctly.
Step 2: Unmarshal parses JSON
json.Unmarshal reads the JSON string bytes and converts them into Go data types.
Step 3: Pointer needed for modification
Passing a pointer to the struct allows Unmarshal to modify the struct fields directly.
Alternative Approaches
package main import ( "encoding/json" "fmt" "strings" ) type Person struct { Name string Age int } func main() { jsonData := `{"Name":"Alice","Age":30}` var p Person decoder := json.NewDecoder(strings.NewReader(jsonData)) err := decoder.Decode(&p) if err != nil { fmt.Println("Error:", err) return } fmt.Println(p) }
package main import ( "encoding/json" "fmt" ) func main() { jsonData := `{"Name":"Alice","Age":30}` var m map[string]interface{} err := json.Unmarshal([]byte(jsonData), &m) if err != nil { fmt.Println("Error:", err) return } fmt.Println(m) }
Complexity: O(n) time, O(n) space
Time Complexity
json.Unmarshal processes each byte of the JSON input once, so time grows linearly with input size.
Space Complexity
It allocates memory for the struct and any intermediate data, proportional to JSON size.
Which Approach is Fastest?
Using json.Unmarshal directly into a struct is fastest and simplest for known JSON formats; using map[string]interface{} adds overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json.Unmarshal to struct | O(n) | O(n) | Known JSON structure, simple parsing |
| json.Decoder | O(n) | O(n) | Streaming JSON or large inputs |
| json.Unmarshal to map | O(n) | O(n) | Unknown or dynamic JSON structure |