简体   繁体   English

Golang 结构数组到 JSON

[英]Golang Array Of Struct To JSON

the code below array struct `数组结构`下面的代码

package main

import (
    "log"
)

type Fruit struct {
    Name     string `json:"name"`
    Quantity int    `json:"quantity"`
}

func main() {
    a := Fruit{Name: "Apple", Quantity: 1}
    o := Fruit{Name: "Orange", Quantity: 2}

    var fs []Fruit
    fs = append(fs, a)
    fs = append(fs, o)
    log.Println(fs)

}

` Running it will generate output as below. ` 运行它将生成如下输出。

[{Apple 1} {Orange 2}]

but i want it like this.但我想要这样。

[{"name":"Apple","quantity":1},{"name":"Orange","quantity":2}]

To achieve the desired output, you can use the json.Marshal() function from the encoding/json package to convert the fs slice of Fruit structs to a JSON array.要获得所需的输出,您可以使用encoding/json包中的json.Marshal()函数将Fruit结构的fs切片转换为 JSON 数组。

Here's an example of how you can do this:以下是如何执行此操作的示例:

package main

import (
    "encoding/json"
    "log"
)

type Fruit struct {
    Name     string `json:"name"`
    Quantity int    `json:"quantity"`
}

func main() {
    a := Fruit{Name: "Apple", Quantity: 1}
    o := Fruit{Name: "Orange", Quantity: 2}

    var fs []Fruit
    fs = append(fs, a)
    fs = append(fs, o)

    // Convert the slice to a JSON array
    jsonArray, err := json.Marshal(fs)
    if err != nil {
        log.Fatal(err)
    }

    // Print the JSON array
    log.Println(string(jsonArray))
}

This will print the desired output:这将打印所需的输出:

[{"name":"Apple","quantity":1},{"name":"Orange","quantity":2}]

It's not enough to annotate your struct, you need the encoding/json package:注释你的结构是不够的,你需要encoding/json包:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM