0
0
GoHow-ToBeginner · 2 min read

Go Program to Convert JSON to Struct

Use json.Unmarshal([]byte(jsonData), &yourStruct) to convert JSON string jsonData into a Go struct yourStruct.
📋

Examples

Input{"Name":"Alice","Age":30}
Output{Name: "Alice", Age: 30}
Input{"Name":"Bob","Age":0}
Output{Name: "Bob", Age: 0}
Input{}
Output{Name: "", Age: 0}
🧠

How to Think About It

To convert JSON to a struct in Go, first define a struct type matching the JSON keys. Then use json.Unmarshal to parse the JSON string into an instance of that struct. This automatically fills the struct fields with the JSON data.
📐

Algorithm

1
Define a struct type with fields matching JSON keys.
2
Get the JSON string input.
3
Create an instance of the struct.
4
Call json.Unmarshal with the JSON bytes and pointer to the struct.
5
Check for errors from Unmarshal.
6
Use the filled struct as needed.
💻

Code

go
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)
}
Output
{Alice 30}
🔍

Dry Run

Let's trace converting JSON '{"Name":"Alice","Age":30}' to struct Person.

1

Define struct Person

Person has fields Name (string), Age (int).

2

Call json.Unmarshal

json.Unmarshal parses JSON bytes and fills struct fields.

3

Struct after Unmarshal

Person{Name: "Alice", Age: 30}

StepActionValue
1Define structPerson{Name string, Age int}
2Unmarshal JSON{"Name":"Alice","Age":30}
3Resulting 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

Use json.Decoder
go
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)
}
json.Decoder is useful for streaming JSON or reading from io.Reader sources.
Use map[string]interface{} first
go
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)
}
Using a map allows flexible JSON parsing but requires manual type assertions.

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.

ApproachTimeSpaceBest For
json.Unmarshal to structO(n)O(n)Known JSON structure, simple parsing
json.DecoderO(n)O(n)Streaming JSON or large inputs
json.Unmarshal to mapO(n)O(n)Unknown or dynamic JSON structure
💡
Always pass a pointer to your struct when using json.Unmarshal to fill its fields.
⚠️
Forgetting to pass the struct as a pointer to json.Unmarshal causes no data to be filled.