如何解决Golang 如何使用不带引号的字段解组 JSON?
我在 []byte
切片中的 JSON 字段没有引号。如何自定义 Golang 的 json.Unmarshal
或预先格式化数据以添加必要的双引号?
示例 (Go Playground):
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Success:
// blob := []byte(`{"license_type": "perpetual","is_trial": false}`)
// Fails:
blob := []byte(`{license_type: "perpetual",is_trial: false}`)
type License struct {
LicenseType string `json:"license_type,omitempty"`
IsTrial bool `json:"is_trial,omitempty"`
}
var license License
if err := json.Unmarshal(blob,&license); err != nil {
fmt.Println("error:",err)
} else {
fmt.Printf("%+v",license)
}
}
error: invalid character 'l' looking for beginning of object key string
此数据是 API 响应的一部分,因此任何后处理都应在不了解结构的情况下完成。
解决方法
解决方案
用yaml解析非标准json,它是json的超集。有效。
通过上面的评论向 @Peter 寻求解决方案:
您可能会成功使用 YAML 解析器,因为它是 JSON 的超集并且引号是可选的。
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
func main() {
blob := []byte(`{license_type: "perpetual",is_trial: true}`)
type License struct {
LicenseType string `yaml:"license_type,omitempty"`
IsTrial bool `yaml:"is_trial,omitempty"`
}
var license License
if err := yaml.Unmarshal(blob,&license); err != nil {
fmt.Println("error:",err)
} else {
fmt.Printf("%+v",license)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。