【问题标题】:How to write this json object in Postgresql with R如何用 R 在 Postgresql 中编写这个 json 对象
【发布时间】:2025-11-23 19:10:01
【问题描述】:
我有这张桌子
CREATE TABLE example (
ID serial NOT NULL PRIMARY KEY,
name varchar(1024),
coords json
);
我想在这个表中写这个json:
[
{
"name": "first",
"coords":{
"lat": 3.14,
"lon": 2.5
}
}
]
我正在尝试使用 jsonlite 和 Rpostgresql,但是出错了
【问题讨论】:
-
has been suggestedodbc 包不支持 JSON 数据类型,因此将其转换为 varchar。有了这个,它应该像在 JSON 化后插入该对象的 character 表示一样简单。您的问题是关于如何将结构化(非字符)数据发布到 JSON 字段中,还是一般如何插入数据?
-
stby,我查看了错误的包......它似乎来自tomoakin/RPostgreSQL#58(于 2013 年开放)指出了类似的限制和解决方法。虽然我没有进行详尽的搜索,但我在 repo 的其他任何地方都没有找到“json”,这表明问题仍然相关且未解决。
标签:
r
postgresql
rstudio
jsonlite
【解决方案1】:
我有一个应用程序,我有 JSON 数据并将其上传到 postgres。在这种情况下,我将 JSON 转换为字符并将其写入数据库。
upload = data.frame(name = name, coords = c(JSONCoords))
dbWriteTable(con, c("table"), value=upload, append=TRUE, row.names=FALSE)
【解决方案2】:
我使用了一个小解决方法。我只是像往常一样将表写入数据库。最后,我将 json 列的数据类型从 text 转换为 jsonb 或 json。下面是一个例子。
library(jsonlite)
library(DBI)
# generate the database connection.
postgres_conn <- dbConnect(RPostgreSQL::PostgreSQL(),
dbname=db,
host=host_db,
port=db_port,
user=db_user,
password=db_password)
# generate the test data.frame.
df <- data.frame(id = 1, name = "username")
df$coords <- toJSON(list(name = "first",
coords = list(lat= "3.14",
lon = "2.5")),
auto_unbox = TRUE)
# write the test dataframe to database
dbWriteTable(postgres_conn, "tbl", df, row.names = FALSE)
# change the format of the column from text to jsonb.
dbSendQuery(postgres_conn, "ALTER TABLE tbl ALTER COLUMN coords TYPE jsonb using coords::jsonb")
在数据库中它看起来像 this。希望这是您想要的。