Home > other >  Golang Array Of Struct To JSON
Golang Array Of Struct To JSON

Time:12-22

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}]

CodePudding user response:

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.

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}]

CodePudding user response:

It's not enough to annotate your struct, you need the encoding/json package:

  • Related