php editor Baicao may encounter an error message when using PHP and PostgreSQL database: "Unable to read json range as pgtype.Int4range". This error usually occurs when trying to convert the JSON data type to the pgtype.Int4range data type. The solution to this problem is not complicated. You only need to convert the JSON data to a string and then perform data type conversion. Next, we will detail how to solve this problem.
I'm trying to read a range into json but I'm having trouble doing json.unmarshal.
This is a test code-
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) }
mistake-
Error while unmarshalling JSON: json: cannot unmarshal string into Go struct field TestPreference.health_range of type pgtype.Int4range.
Is it possible to read it as pgtype.int4range? I guess this type is for database use only? fwiw, I'm using pgx github.com/jackc/pgx/v4
It doesn't work because "[20,30)"
is not a struct A valid json value for pgtype.int4range
, and pgtype.int4range does not yet implement the json.unmarshaler interface.
You must implement the interface to unmarshal yourself "[20,30)"
:
type myint4range pgtype.int4range func (r *myint4range) unmarshaljson(b []byte) error { return (*pgtype.int4range)(r).decodetext(nil, bytes.trim(b, `"`)) }
by the way
assert.equal(t, 20, update.healthrange.lower)
Comparing two different types, should be corrected to:
assert.Equal(t, int32(20), update.HealthRange.Lower.Int)
View the full demo here: https://www.php.cn/link/fbf6e9ffad68f73e466198206987dedc一个>.
The above is the detailed content of Unable to read json range into pgtype.Int4range. For more information, please follow other related articles on the PHP Chinese website!