首页 > 解决方案 > 使用 Go 解析 JSON 中包含 unicode 字符的键

问题描述

我有这样的 API 响应:

{ 
  "Pass ✔": true
}

在 Go 中,我使用以下代码:

type Status struct {
  Pass bool `json:"Pass ✔"`
}

// ...

var s Status

json.Unmarshal(body, &s)

fmt.Println(s.Pass) // false, where it should be true

如何正确解组此 JSON 文档?

标签: jsongo

解决方案


正如其他人提到的,目前不可能这样做。作为一种解决方法,您可以执行以下操作:

package main

import (
   "encoding/json"
   "fmt"
)

type status map[string]bool

func (s status) pass() bool {
   return s["Pass ✔"]
}

func main() {
   data := []byte(`{"Pass ✔": true}`)
   var stat status
   json.Unmarshal(data, &stat)
   pass := stat.pass()
   fmt.Println(pass) // true
}

推荐阅读