如何使用 R 在 Postgresql 中编写此 json 对象
How to write this json object in Postgresql with R
我有这个table
CREATE TABLE example (
ID serial NOT NULL PRIMARY KEY,
name varchar(1024),
coords json
);
而且我想把这个json写在这个table中:
[
{
"name": "first",
"coords":{
"lat": 3.14,
"lon": 2.5
}
}
]
我正在尝试使用 jsonlite 和 Rpostgresql,但出现错误
我有应用程序,我有 JSON 数据并将其上传到 postgres。在这种情况下,我将 JSON 转换为字符并将其写入数据库。
upload = data.frame(name = name, coords = c(JSONCoords))
dbWriteTable(con, c("table"), value=upload, append=TRUE, row.names=FALSE)
我使用了一个小的解决方法。我只是像往常一样将 table 写入数据库。最后,我将 json 列的数据类型从文本转换为 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")
在数据库中它看起来像这样。希望这就是你想要的。
我有这个table
CREATE TABLE example (
ID serial NOT NULL PRIMARY KEY,
name varchar(1024),
coords json
);
而且我想把这个json写在这个table中:
[
{
"name": "first",
"coords":{
"lat": 3.14,
"lon": 2.5
}
}
]
我正在尝试使用 jsonlite 和 Rpostgresql,但出现错误
我有应用程序,我有 JSON 数据并将其上传到 postgres。在这种情况下,我将 JSON 转换为字符并将其写入数据库。
upload = data.frame(name = name, coords = c(JSONCoords))
dbWriteTable(con, c("table"), value=upload, append=TRUE, row.names=FALSE)
我使用了一个小的解决方法。我只是像往常一样将 table 写入数据库。最后,我将 json 列的数据类型从文本转换为 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")
在数据库中它看起来像这样