I used a small workaround. I just write the table to database as usual. At last, I cast the datatype of the json column from text to jsonb or json. In the following is an example.
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")
In the database it looks like this
. Hopefully this is what you want.