Answers for "struct to json golang"

1

golang struct to json output

package main
import (
    "encoding/json"
    "fmt"
    "log"
)
type employee1 struct {
    Name   string `json:"n"`
    Age    int    `json:"a"`
    salary int    `json:"s"`
}
type employee2 struct {
    Name   string
    Age    int
    salary int
}
func main() {
    e1 := employee1{
        Name:   "John",
        Age:    21,
        salary: 1000,
    }
    j, err := json.Marshal(e1)
    if err != nil {
        log.Fatalf("Error occured during marshaling. Error: %s", err.Error())
    }
    fmt.Printf("employee1 JSON: %sn", string(j))
    e2 := employee2{
        Name:   "John",
        Age:    21,
        salary: 1000,
    }
    j, err = json.Marshal(e2)
    if err != nil {
        log.Fatalf("Error occured during marshaling. Error: %s", err.Error())
    }
    fmt.Printf("nemployee2 JSON: %sn", string(j))
}
Posted by: Guest on June-27-2021
0

golang struct to bson.d

func toDoc(v interface{}) (doc *bson.Document, err error) {
    data, err := bson.Marshal(v)
    if err != nil {
        return
    }

    err = bson.Unmarshal(data, &doc)
    return
}
Posted by: Guest on May-05-2020
0

go change json key struct

type Person struct {
  Name string `json:"person_name"`
  Surname string `json:"person_surname"`
}

func main(){
  Bytes, err := json.Marshal(Person{"Joe", "Soap"})
  if err != nil {
    log.Fatal(err.Error())
  }
  fmt.Println(string(Bytes))
}
Posted by: Guest on June-12-2020
0

golang json to struct

type response2 struct {
    Page   int      `json:"page"`
    Fruits string `json:"fruits"`
}
Posted by: Guest on October-16-2021

Code answers related to "struct to json golang"

Browse Popular Code Answers by Language