卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35111本站已运行394

无法将 json 范围读取为 pgtype.Int4range

无法将 json 范围读取为 pgtype.int4range

php小编百草在使用PHP与PostgreSQL数据库时,可能会遇到一个错误提示:“无法将 json 范围读取为 pgtype.Int4range”。这个错误通常发生在尝试将JSON数据类型转换为pgtype.Int4range数据类型时。这个问题的解决方法并不复杂,只需要将JSON数据转换为字符串,然后再进行数据类型转换即可。接下来,我们将详细介绍如何解决这个问题。

问题内容

我正在尝试将范围读取为 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 github.com/jackc/pgx/v4

解决方法

它不起作用,因为 "[20,30)" 不是结构 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://www.php.cn/link/fbf6e9ffad68f73e466198206987dedc一个>.

卓越飞翔博客
上一篇: 解析shell脚本中的URL
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏