Home > Backend Development > Golang > How to return json in golang

How to return json in golang

王林
Release: 2023-05-15 13:29:37
Original
1477 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template