S
S
Sinot2016-07-29 15:17:04
go
Sinot, 2016-07-29 15:17:04

How to convert structure to JSON?

Greetings!
And straight to the point.

package main

import (
  "fmt"
  "encoding/json"
)

type Department struct {
  Id int
  Name string
  Phone string
}

func main() {
  a := Department {1, "test", "12-32"}
  fmt.Println(a)

  b, _ := json.Marshal(a)
  fmt.Println(string(b))
}

{1 test 12-32}
{"Id":1,"Name":"test","Phone":"12-32"}

But if the name of the property in the structure is lowercase:
package main

import (
  "fmt"
  "encoding/json"
)

type Department struct {
  Id int
  name string
  Phone string
}

func main() {
  a := Department {1, "test", "12-32"}
  fmt.Println(a)

  b, _ := json.Marshal(a)
  fmt.Println(string(b))
}

{1 test 12-32}
{"Id":1,"Phone":"12-32"}

Why and most importantly how to win?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2016-07-29
@Sinot

I will add. In order for json to display fields with a small letter, you need to register a tag.

type Department struct {
  Id int `json:"id"`
  Name string `json:"name"`
  Phone string `json:"phone"`
}

`json:"name"` - you can write anything instead of name, in json this field will be under that name.
For example:
type Department struct {
  Id int `json:"id"`
  Name string `json:"name"`
  Phone string 
  AnyField string `json:"part"`
}

will bring out
{id: 123, name: "Имя", Phone: "123", part: "AnyField"}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question