将JSON.RawMessage转换为JSON

问题描述

我正在使用gqlgensqlxpgx。而且我正在尝试为sqlx的{​​{1}}使用自定义标量。

我在项目表中具有此属性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
);

我有这个graphql模式:

// 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

我可以成功插入数据库,但检索时出错。

// 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

但是我得到的是字符串而不是json:

...

  Attributes:
    model:
      - github.com/my-api/graph/model.Attributes

所需的输出是:

{
  "data": {
    "item": {
      "id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba","quantity": 100,"attributes": "eyJjb2xvciI6ICJyZWQifQ==",}
  }
}

我做错了什么?


这是我的尝试:

如果我从Item结构的Attributes中删除了指针,则{ "data": { "item": { "id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba","attributes": { "size": "medium","color": "red",} } } } 会引发错误

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))
}

解决方法

Attributes使用types.JSONText定义,json.RawMessage使用[]byte定义的enter link description here定义。这意味着所有4种类型的基础类型,包括[]byte []byte,这意味着这4种类型都可以转换为[]byte

因此,这样做就足够了:

func (a *Attributes) MarshalGQL(w io.Writer) {
    w.Write([]byte(*a))
}