Home > Backend Development > Golang > How to read json data in golang

How to read json data in golang

Release: 2020-01-15 10:20:10
Original
4441 people have browsed it

How to read json data in golang

JSON (JavaScript Object Notation) is a more lightweight data exchange format than XML. It is easy for people to read and write, and it is also easy for programs to parse and generate.

Go languageBuilt-in support for JSON. Using the encoding/json standard library built into the GO language, developers can easily use GO programs to generate and parse data in JSON format.

Example:

package main
import (
    "encoding/json"
    "fmt"
)
type Book struct {
    Title       string
    Author      []string
    Publisher   string
    Price       float64
    IsPublished bool
}
func main() {
    b := []byte(`{
    "Title":"go programming language",
    "Author":["john","ada","alice"],
    "Publisher":"qinghua",
    "IsPublished":true,
    "Price":99
  }`)
//先创建一个目标类型的实例对象,用于存放解码后的值
    var book Book
    err := json.Unmarshal(b, &book)
    if err != nil {
        fmt.Println("error in translating,", err.Error())
        return
    }
    fmt.Println(book.Author)
}
Copy after login

The Json.Unmarshal() function will search for fields in the target structure according to an agreed order, and match if one is found. These fields must all be exportable fields starting with a capital letter in the type declaration.

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of How to read json data in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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