This page looks best with JavaScript enabled

json

 ·  ☕ 2 min read

json package

json package is part of Go standard library. It providers useful types and functions that can be used to work with json data and Go data types.

installation

json package is part of standard Go library at encoding/json

usage

There are two main operation defined while working with json,

  1. Marshaling : Marshaling is conversion of Go data types to json.
  2. Unmarshaling : Converting json to Go data type.

field tags

Fields tags help in representation of data when name of struct fields and json fields need to be different or when it is required to export selected fields from struct to json.

  • FirstName in Go data struct is represented as first_name in json.
1
2
3
type User struct {
	FirstName string `json:"first_name"`
}

marshal.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
  "encoding/json"
  "fmt"
  "log"
)

type Student struct {
  Name string
  Id   int
}

func main() {
  students := []Student{
      {
          Name: "Sumit",
          Id:   1,
      },
      {
          Name: "Amit",
          Id:   2,
      },
  }

  j, err := json.Marshal(students)
  if err != nil {
      log.Fatalf("Error in Marshalling, %s", err)
  }
  fmt.Printf("%s\n", j) // [{"Name":"Sumit","Id":1},{"Name":"Amit","Id":2}]
}

unmarshal.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main

import (
  "encoding/json"
  "fmt"
  "log"
  "net/http"
)

//UserResponse generated from https://mholt.github.io/json-to-go/
type UserResponse struct {
  Page       int `json:"page"`
  PerPage    int `json:"per_page"`
  Total      int `json:"total"`
  TotalPages int `json:"total_pages"`
  Data       []struct {
      ID        int    `json:"id"`
      Email     string `json:"email"`
      FirstName string `json:"first_name"`
      LastName  string `json:"last_name"`
      Avatar    string `json:"avatar"`
  } `json:"data"`
}

func main() {

  var result UserResponse

  response, err := http.Get("https://reqres.in/api/users?page=1")
  if err != nil {
      log.Fatalf("Unable to connect, %s", err)
  }

  err = json.NewDecoder(response.Body).Decode(&result)
  defer response.Body.Close()

  if err != nil {
      log.Fatalf("Unable to parse, %s", err)
  }

  for _, user := range result.Data {
      fmt.Printf("User= %s %s, Id=%d, Email=%s\n", user.FirstName, user.LastName, user.ID, user.Email)
  }

}

package source and documentation

https://pkg.go.dev/encoding/json?tab=doc


Sumit
WRITTEN BY
Sumit
Gopher


What's on this Page