将 JSON.RawMessage 转换为 JSON字符串
时间:2024-02-25
浏览:257
作者:佚名
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《将 JSON.RawMessage 转换为 JSON字符串》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
问题内容
我正在使用 gqlgen、sqlx 和 pgx。我正在尝试对 sqlx 的 types.jsontext 使用自定义标量。
我在项目表中有此属性 jsonb 字段。
-- migrations/001_up.sql
create table if not exists items (
id uuid primary key default uuid_generate_v4(),
quantity int not null,
attributes jsonb
);
我有这些模型结构:
// graph/model/item.go
type item struct {
id string `json:"id,omitempty" db:"id,omitempty"`
quantity int `json:"quantity" db:"quantity"`
attributes *attributes `json:"attributes,omitempty" db:"attributes,omitempty"`
}
type attributes types.jsontext
我有这个 graphql 架构:
// graph/schema.graphql
type item {
id: id!
quantity: int!
attributes: attributes
}
scalar attributes
我可以成功插入数据库,但检索时出错。
| id | quantity | attributes |
|---------------|----------|------------------------------------|
| 031e1489-... | 100 | {"size": "medium", "color": "red"} |
这是我从数据库查询得到的日志:
>> items.db: &{
031e1489-02c9-46d3-924d-6a2edf1ca3ba // id
100 // quantity
0xc000430600 // attributes
}
我尝试封送属性标量:
// graph/model/item.go
...
func (a *attributes) marshalgql(w io.writer) {
b, _ := json.marshal(a)
w.write(b)
}
// unmarshal here
...
在 gqlgen.yml 中添加自定义标量类型:
...
attributes:
model:
- github.com/my-api/graph/model.attributes
但是我得到的是字符串而不是 json:
{
"data": {
"item": {
"id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba",
"quantity": 100,
"attributes": "eyjjb2xvcii6icjyzwqifq==",
}
}
}
所需的输出是:
{
"data": {
"item": {
"id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba",
"quantity": 100,
"attributes": {
"size": "medium",
"color": "red",
}
}
}
}
我做错了什么?
这是我的尝试:
如果我从 item 结构中的属性中删除指针,gqlgen 会抛出错误:
go generate ./... go: finding module for package github.com/my-api/graph/generated generating core failed: type.gotpl: template: type.gotpl:49:28: executing "type.gotpl" at <$type.elem.go>: nil pointer evaluating *config.typereference.goexit status 1 graph/resolver.go:3: running "go": exit status 1 make: *** [makefile:2: gengql] error 1
这会返回所需的结果,但我不知道如何将其与真实数据一起使用:
func (a *attributes) marshalgql(w io.writer) {
raw := json.rawmessage(`{"foo":"bar"}`)
j, _ := json.marshal(&raw)
s := string(j)
w.write([]byte(s))
}
查询结果:
{
"data": {
"item": {
"id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba",
"quantity": 100,
"attributes": {
"foo": "bar"
}
}
}
}解决方案
attributes 使用 types.JSONText 定义,而 types.JSONText 使用 json.RawMessage 定义,而 json.RawMessage 使用 []byte 定义。这意味着所有 4 种类型(包括 []byte)的底层类型是 []byte,这又意味着所有 4 种类型都可以转换至 []byte。
因此,这样做应该足够了:
func (a *Attributes) MarshalGQL(w io.Writer) {
w.Write([]byte(*a))
}好了,本文到此结束,带大家了解了《将 JSON.RawMessage 转换为 JSON字符串》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
