首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-02-10 09:00:09
转载
378 人浏览过

无法将 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一个>.

以上是无法将 json 范围读取为 pgtype.Int4range的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!