登录
首页 >  Golang >  Go问答

使用 Go 解析 JSON 中包含 unicode 字符的密钥

来源:stackoverflow

时间:2024-04-14 16:27:28 263浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《使用 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 文档?


正确答案


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

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
}

本篇关于《使用 Go 解析 JSON 中包含 unicode 字符的密钥》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>