Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page
  • Byte 轉為 JSON
  • Struct to JSON
  • 快速 JSON 轉為 struct 的工具

Was this helpful?

  1. 基本語法

JSON

Byte 轉為 JSON

使用 json.Unmarshal 並傳入要轉換的 []byte 格式的 body 即可,如果是用 string(body) 則回傳的結果會是 JSON stringify 的型態(多了 \ 在每個 key 前面)

func GetUserAssets(c *fiber.Ctx) error {
	url := "https://api.....io/api/v1/assets...."

	req, _ := http.NewRequest("GET", url, nil)

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	var data interface{}
	json.Unmarshal(body, &data)
	return c.Status(fiber.StatusCreated).JSON(fiber.Map{
		"data":    data,
		"success": true,
		"message": "User assets get successfully",
	})
}

Struct to JSON

記得 struct 的 key 開頭要大寫,然後 Marshal 後要轉為 string

  var results struct {
		Traders_24H string `json:"Traders_24H"`
	}

  results.Traders_24H = "test"
	
	var data, err1 = json.Marshal(results)
	
	if err1 != nil {
		log.Fatal(err)
	}

	return c.Status(fiber.StatusOK).JSON(fiber.Map{
		"success": true,
		"data":    string(data),
		"message": "success query NFT market data",
	})

快速 JSON 轉為 struct 的工具

PreviousBSONNext時間相關

Last updated 3 years ago

Was this helpful?

https://mholt.github.io/json-to-go/