我正在try 将范围读取为json,但在执行json.unmarshal时我发现了一个问题.

这是一个测试代码-

import (
    "encoding/json"
    "testing"

    "github.com/jackc/pgtype"
    "github.com/stretchr/testify/assert"
)

type TestHealthPreference struct {
    HealthRange pgtype.Int4range `json:"health_range"`
    ID          string           `json:"id"`
}

// just a test to make sure unmarshaling works
func TestPreferenceUpdateUnmarshal(t *testing.T) {
    jsonData := `{
        "health_range": "[20,30)",
        "id": "123"
    }`

    var update TestHealthPreference
    err := json.Unmarshal([]byte(jsonData), &update)
    if err != nil {
        t.Errorf("Error while unmarshalling JSON: %v", err)
    }

    assert.Equal(t, 20, update.HealthRange.Lower)
}

这是个错误.

Error while unmarshalling JSON: json: cannot unmarshal string into Go struct field TestPreference.health_range of type pgtype.Int4range. 

是否可以将其读作pgtype.Int4range?我猜这种类型只能用于数据库吧?FWIW,我正在使用PGx githorb.com/jackc/pgx/v4

推荐答案

它不起作用,因为"[20,30)"不是 struct pgtype.Int4range的有效JSON值,而pgtype.Int4range还没有实现json.Unmarshaler接口.

您必须自己实现接口才能解组"[20,30)":

type myInt4range pgtype.Int4range

func (r *myInt4range) UnmarshalJSON(b []byte) error {
    return (*pgtype.Int4range)(r).DecodeText(nil, bytes.Trim(b, `"`))
}

顺便一提

assert.Equal(t, 20, update.HealthRange.Lower)

比较两种不同的类型,应更正为:

assert.Equal(t, int32(20), update.HealthRange.Lower.Int)

点击此处查看完整的演示:https://go.dev/play/p/gGNj3kOBB8k.

Postgresql相关问答推荐

无法在PostgreSQL中创建方案和表

列索引8上的扫描错误,名称已复制:不支持扫描,正在存储驱动程序.值类型[]uint8到类型*[]*bool

如何在PostgreSQL 16中设置&Q;VARSIZE&Q;和&Q;SET_VARSIZE&Q;

为什么Postgres在打印时能完全缩短时间跨度?

Psql:Windows 10上奇怪的错误输出编码

如何创建一个触发器来传播对主键表的更新?

如何在 sequelize 使用 db postgres 中通过外键更新记录和更新包含许多记录关系

Cloud SQL 时间点 数据驻留

为什么 postgresql 可以在这个查询中高效地使用索引?

PostgreSQL - 如何获得前一个月和一周的价值?

如何在 psycopg2 中使用服务器端游标

org.postgresql.util.PSQLException:错误:relation "app_user" does not exist

Select 空字段

为 Django Postgres 连接强制 SSL

在同一分区上应用多个窗口函数

当成功有时会导致退出代码为 1 时,如何可靠地确定 pg_restore 是否成功?

在 PostgreSQL 中的表上禁用 DELETE?

Rails PG::UndefinedTable:错误:missing FROM-clause entry for table

使用 RPostgreSQL 写入特定模式

有没有办法确保 WHERE 子句在 DISTINCT 之后发生?