Go provides encoding/json packages to easily process JSON data. 1. Use json.Marshal to encode the Go structure or map into JSON. The structure field must start with capital letters and specify the key name through the json:"name" tag. Omitempty can make the zero-value field omitted; 2. Use json.Unmarshal to decode the JSON data into a Go variable, and a variable pointer must be passed in order to modify the value; 3. For JSON with unknown structure, it can be decoded into map[string]interface{} or interface{}, but type assertions are required when accessing; 4. When processing large JSON files or streaming data, use json.Encoder and json.Decoder can achieve efficient incremental processing to avoid loading all data at once. Always check for errors to ensure that JSON is formatted correctly and has type matching, Go's JSON support is suitable for scenarios such as API development, configuration reads, and data processing.
Working with JSON in Go is straightforward thanks to the built-in encoding/json
package. Go provides easy ways to encode (marshal) Go data structures into JSON and decode (unmarshal) JSON data into Go values.

Here's how you typically work with JSON in Go:
1. Encoding (Go → JSON) with json.Marshal
You use json.Marshal
to convert Go structs or maps into JSON.

package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Email string `json:"email,omitempty"` } func main() { p := Person{Name: "Alice", Age: 30} data, err := json.Marshal(p) if err != nil { panic(err) } fmt.Println(string(data)) // {"name":"Alice","age":30} }
- The
json:"name"
tag tells Go what the JSON key should be. -
omitempty
means the field will be omitted if it has a zero value (eg, empty string, 0, nil).
2. Decoding (JSON → Go) with json.Unmarshal
Use json.Unmarshal
to parse JSON data into a struct or map.
jsonData := `{"name": "Bob", "age": 25, "email": "bob@example.com"}` var p Person err := json.Unmarshal([]byte(jsonData), &p) if err != nil { panic(err) } fmt.Printf("% v\n", p) // {Name:Bob Age:25 Email:bob@example.com}
Note: You must pass a pointer to the variable (
&p
) soUnmarshal
can modify it.
3. Working with Dynamic or Unknown JSON
If you don't know the structure of the JSON, you can use map[string]interface{}
or interface{}
.
var data map[string]interface{} err := json.Unmarshal([]byte(jsonData), &data) if err != nil { panic(err) } fmt.Println(data["name"]) // Bob
You can also decode into []interface{}
for arrays.
?? Be careful: you'll need type assertions when accessing values.
4. Streaming JSON: json.Encoder
and json.Decoder
For handling large JSON files or HTTP streams, use json.Encoder
and json.Decoder
.
Writing JSON to an HTTP response or file:
encoder := json.NewEncoder(writer) // eg, http.ResponseWriter or os.File err := encoder.Encode(person)
Reading JSON from a request body or file:
decoder := json.NewDecoder(reader) var person Person err := decoder.Decode(&person)
These are efficient because they process data incrementally, not all at once.
Key Tips
- Struct fields must be exported (start with a capital letter) to be JSON-marshalable.
- Use struct tags to control field names, omitempty, string formatting (eg,
json:",string"
for numbers-as-strings). -
time.Time
fields can be serialized automatically if formatted properly. - Always check for errors — malformed JSON or type mismatches will return errors during unmarshaling.
Basically, Go's encoding/json
gives you a clean, efficient way to handle JSON whether you're building APIs, reading config files, or processing data. Just define your structs, use tags wisely, and lean on Marshal
/ Unmarshal
or the streaming Encoder
/ Decoder
as needed.
The above is the detailed content of How do you work with JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go's template engine provides powerful dynamic content generation capabilities through text/template and html/template packages, where html/template has automatic escape function to prevent XSS attacks, so it should be used first when generating HTML. 1. Use {{}} syntax to insert variables, conditional judgments and loops, such as {{.FieldName}} to access structure fields, {{if}} and {{range}} to implement logical control. 2. The template supports Go data structures such as struct, slice and map, and the dot in the range represents the current iterative element. 3. The named template can be defined through define and reused with the template directive. 4.ht

Go and Kafka integration is an effective solution to build high-performance real-time data systems. The appropriate client library should be selected according to needs: 1. Priority is given to kafka-go to obtain simple Go-style APIs and good context support, suitable for rapid development; 2. Select Sarama when fine control or advanced functions are required; 3. When implementing producers, you need to configure the correct Broker address, theme and load balancing strategy, and manage timeouts and closings through context; 4. Consumers should use consumer groups to achieve scalability and fault tolerance, automatically submit offsets and use concurrent processing reasonably; 5. Use JSON, Avro or Protobuf for serialization, and it is recommended to combine SchemaRegistr

govetcatchescommonlogicalerrorsandsuspiciousconstructsinGocodesuchas1)misuseofprintf-stylefunctionswithincorrectarguments,2)unkeyedstructliteralsthatmayleadtoincorrectfieldassignments,3)sendingtoclosedchannelswhichcausespanics,4)ineffectiveassignment

Usereflect.ValueOfandreflect.TypeOftogetruntimevaluesandtypes;2.Inspecttypedetailswithreflect.TypemethodslikeName()andKind();3.Modifyvaluesviareflect.Value.Elem()andCanSet()afterpassingapointer;4.CallmethodsdynamicallyusingMethodByName()andCall();5.R

In Go language, HTTP middleware is implemented through functions, and its core answer is: the middleware is a function that receives and returns http.Handler, used to execute general logic before and after request processing. 1. The middleware function signature is like func (Middleware(nexthttp.Handler)http.Handler), which achieves functional expansion by wrapping the original processor; 2. The log middleware in the example records the request method, path, client address and processing time-consuming, which is convenient for monitoring and debugging; 3. The authentication middleware checks the Authorization header, and returns 401 or 403 errors when verification fails to ensure secure access; 4. Multiple middleware can be nested to adjust

Usecontext.WithTimeouttocreateacancellablecontextwithadeadlineandalwayscallcancel()toreleaseresources.2.ForHTTPrequests,settimeoutsusinghttp.Client.Timeoutorusecontextviahttp.NewRequestWithContextforper-requestcontrol.3.Ingoroutineswithchannels,usese

UsestructswithPERJSontagsFeRpredictabledatoensurefast, safeparsingwithcompile-timetypesafety.2.avoidmap [string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] interface {string] }duetoreflectionoverheadandruntimetypeassertionsunlessdealingwithtrulydynamicJSON.3.Usejson.RawMessagefordeferredorselectivep

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.
