Go map to JSON: convert, print, and parse back with encoding/json

Golang map to JSON and JSON string: json.Marshal and string(bytes) to convert map to json golang, MarshalIndent and Encoder to print map as JSON, then json.Unmarshal for json to map golang (map[string]any) with encoding/json.

Published

Updated

Read time 3 min read

Reviewed byDeepak Prasad

Go map to JSON: convert, print, and parse back with encoding/json

People land here from searches like golang map to json, go map to json, golang convert map to json string, or golang print map as json — all of that is encoding/json in practice. Marshal turns a map into bytes you can cast to a JSON string; json.Unmarshal handles json to map golang and golang json to map when you parse API or file data back into a map[string]any (or a struct). This guide uses small main examples for marshal, encoder output, indentation, and reverse parsing. For larger typed documents, pair this with JSON unmarshal in Go.

Tested with Go 1.24 on Linux.


Convert a map to JSON (json.Marshal)

json.Marshal turns any JSON-marshalable value into a []byte and an error. For a map, use string keys (map[string]T); that matches JSON objects. To get a golang map to json string, convert the bytes:

go
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	m := map[string]int{"one": 1, "two": 2, "three": 3}
	b, err := json.Marshal(m)
	if err != nil {
		fmt.Println("marshal:", err)
		return
	}
	fmt.Println(string(b))
}
Output

You should see one line of JSON with the three keys (order may vary between runs because map iteration is not sorted).


Write JSON with json.NewEncoder (streams and io.Writer)

json.NewEncoder(w).Encode(v) writes JSON to w and appends a newline. Use it for HTTP responses, files, or a bytes.Buffer when you prefer streaming over building a single []byte.

go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

func main() {
	m := map[string]int{"one": 1, "two": 2, "three": 3}
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	if err := enc.Encode(m); err != nil {
		fmt.Println("encode:", err)
		return
	}
	fmt.Print(buf.String())
}
Output

The buffer ends with a trailing newline from Encode.


Pretty-print: json.MarshalIndent and indented encoders

To golang print map as json in a readable shape, use json.MarshalIndent(v, prefix, indent) or set indent on an encoder.

go
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	m := map[string]any{
		"name": "Some User",
		"age":  35,
		"address": map[string]string{
			"street": "Random St",
			"city":   "Some town",
			"state":  "Some state",
			"zip":    "12345",
		},
	}
	b, err := json.MarshalIndent(m, "", "  ")
	if err != nil {
		fmt.Println("marshal:", err)
		return
	}
	fmt.Println(string(b))
}
Output

You should see nested JSON with two-space indentation.


JSON to map: json.Unmarshal

To parse JSON back into a map — the reverse of map to JSON — use json.Unmarshal on your bytes. A flexible choice is map[string]any so nested JSON objects become nested maps:

go
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	const s = `{"name":"Ada","score":99,"ok":true}`
	var out map[string]any
	if err := json.Unmarshal([]byte(s), &out); err != nil {
		fmt.Println("unmarshal:", err)
		return
	}
	fmt.Println(out["name"], out["score"], out["ok"])
}
Output

You should see Ada, 99, and true (numeric JSON values decode as float64 in any; use a struct or json.Decoder with UseNumber if you need exact number handling). For stable field types and validation, unmarshal into a struct instead; see JSON unmarshal in Go.


Summary

You now have a practical path for map to JSON and back with encoding/json: json.Marshal plus string([]byte) for a compact JSON string, json.NewEncoder when you already have an io.Writer, and json.MarshalIndent (or Encoder.SetIndent) when you want readable JSON in logs or responses. Parsing uses json.Unmarshal into map[string]any for flexible shapes, or into structs when you want typed fields and clearer validation — see the linked unmarshal guide. Remember that JSON numbers stored in any decode as float64 unless you opt into different handling, and that map key order in generated JSON is not sorted. Check marshal and unmarshal errors on every call before trusting the result.


References


Frequently Asked Questions

1. How do I golang convert map to json or get a golang map to json string?

Call json.Marshal on the map, check the error, then use string on the returned []byte; that is the compact JSON text without extra formatting.

2. What is the difference between json.Marshal and json.NewEncoder?

Marshal returns a byte slice you can turn into a string; NewEncoder writes JSON to an io.Writer such as os.Stdout or a bytes.Buffer, which suits streaming or HTTP responses.

3. How do I golang print map as json with indentation?

Use json.MarshalIndent with prefix and indent strings, or configure json.Encoder with SetIndent; both produce multi-line JSON for logs or debugging.

4. How does json to map golang work?

Pass a pointer to map[string]any or a struct pointer into json.Unmarshal with your JSON bytes; object keys become map keys and nested objects become nested maps unless you unmarshal into structs.

5. Why does my JSON object key order change between runs?

encoding/json walks Go map iteration order, which is not sorted; for stable key order use a struct field list or sort keys yourself before emitting JSON.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …