gpt4 book ai didi

json - Rust使用Postgres JSON属性: cannot convert between the Rust type `alloc::string::String` and the Postgres type `jsonb`

转载 作者:行者123 更新时间:2023-12-03 11:34:08 27 4
gpt4 key购买 nike

目前,我可以使用以下代码,但是我不想将JSON转换为postgres查询中的文本,因为它增加了延迟。

async fn reverse_geocode(min : f32, max : f32, pool: &Pool) -> Result<String, PoolError> {
let client: Client = pool.get().await?;
let sql = format!("select \"json\"::TEXT from get_data({}, {})", min, max);
let stmt = client.prepare(&sql).await?;
let rows = client.query(&stmt, &[]).await?;
Ok(rows[0].get(0))
}
如果我不将JSON转换为文本,则会出现以下错误:
error retrieving column 0: error deserializing column 0: cannot convert between the Rust type `alloc::string::String` and the Postgres type `jsonb`
可以使用什么类型,以便我返回该json值而不将其转换为文本?

最佳答案

为了使用Json和Jsonb值,您需要在postgres create中启用以下功能:features = ["with-serde_json-1"]然后您可以将返回类型更改为Result<serde_json::Value,PoolError>这样您就可以在cargo.toml中

[dependencies]
postgres = {version = "0.17.3" , features = ["with-serde_json-1"] }
serde_json = "1.0.56"
并在您的main.rs中
async fn reverse_geocode(min : f32, max : f32, pool: &Pool) -> Result<serde_json::Value, PoolError> {
let client: Client = pool.get().await?;
let sql = format!("select \"json\" from get_data({}, {})", min, max);
let stmt = client.prepare(&sql).await?;
let rows = client.query(&stmt, &[]).await?;
Ok(rows[0].get(0))
}

关于json - Rust使用Postgres JSON属性: cannot convert between the Rust type `alloc::string::String` and the Postgres type `jsonb` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62692263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com