How to return json in golang
When developing websites or web applications, it is often necessary to return JSON data in the form of APIs. Therefore, it is crucial to master how to return JSON data in Golang.
This article will introduce Golang’s json package and its basic usage, and how to use it to encode Golang data structures into JSON strings or decode JSON strings into Golang data structures.
- Basic usage
In Golang programs, it is very simple to use the json package to operate JSON data. JSON strings can be parsed into Golang variables, and Golang variables can be encoded into JSON strings.
- Encode Golang variables into JSON strings
In the Golang program, if you need to encode Golang variables into JSON strings, you can use the json.Marshal() function to complete this task. The following is a sample program that demonstrates how to encode a Go structure into a JSON string:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { p := Person{"Tom", 30} b, err := json.Marshal(p) if err != nil { fmt.Println("error:", err) return } fmt.Println(string(b)) }
The output is:
{"Name":"Tom","Age":30}
In the above sample program, the Person structure contains two fields Name and Age. We instantiate it as a variable called p and pass it to the json.Marshal() function. The function will return a byte array of JSON string and an optional error.
If JSON encoding fails, a non-null error will be returned. In the above example, we check for errors and print error messages.
Note: When using json.Marshal() to encode a JSON string, the name of the JSON field is the name of the structure field and must start with a capital letter.
- Decode JSON string into Golang variable
In Golang program, if you need to decode JSON string into Golang variable, you can use the json.Unmarshal() function . The following is a sample program that demonstrates how to decode a JSON string into a Go structure:
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { jsonStr := `{"Name":"Tom","Age":30}` var p Person err := json.Unmarshal([]byte(jsonStr), &p) if err != nil { fmt.Println("error:", err) return } fmt.Println(p.Name, p.Age) }
The output result is:
Tom 30
In the above sample program, we decode the JSON string with the empty The Person structure is decoded. The JSON string needs to be converted into a byte array, which is modified to accommodate the decoded results. The decoded results will be stored in unmarshaled variables.
A & operator is used here to pass the variable address to the function and use it to modify the actual result.
Similarly, if JSON decoding fails, an error will be returned and the error message will be printed.
- Return JSON data
In Golang, you can use the net/http package to create an API and return JSON data. The following is a simple sample program that demonstrates how to return JSON data using Golang:
package main import ( "encoding/json" "fmt" "net/http" ) type Person struct { Name string Age int } func main() { http.HandleFunc("/person", handlePerson) http.ListenAndServe(":8080", nil) } func handlePerson(w http.ResponseWriter, r *http.Request) { p := Person{"Tom", 30} b, err := json.Marshal(p) if err != nil { fmt.Println("error:", err) return } w.Header().Set("Content-Type", "application/json") w.Write(b) }
In the above sample program, we created a basic HTTP server, using the net/http package. We use the http.HandleFunc() function to bind the path /person to the handlePerson handler function.
The handlePerson function returns a Person structure with Name and Age fields. It will encode the Person structure into JSON format using the json.Marshal() function. Finally, we use the http.ResponseWriter interface to write the JSON response. Before writing, we use the w.Header().Set() function to set the Content-Type of the response header to application/json.
Now, you know how to encode and decode JSON data using Golang, and how to return JSON data in an HTTP response. Learning these skills will make you more comfortable developing web applications.
The above is the detailed content of How to return json in golang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...
