Home Backend Development Golang How to return json in golang

How to return json in golang

May 15, 2023 pm 01:29 PM

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.

  1. 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.

  1. 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))
}
Copy after login

The output is:

{"Name":"Tom","Age":30}
Copy after login

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.

  1. 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)
}
Copy after login

The output result is:

Tom 30
Copy after login

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.

  1. 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)
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

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.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

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

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

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

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

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

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

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

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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,...

See all articles