【问题标题】:Converting JSON file to SQLite file将 JSON 文件转换为 SQLite 文件
【发布时间】:2020-07-27 21:32:36
【问题描述】:

我正在编写一个函数,通过在表中表示 JSON 文件将其转换为 SQLite 文件,但我在索引没有键的对象时遇到了一点麻烦。例如,我正在转换这个 JSON 文件,但不确定如何正确索引它。

[ [ "A1", "A2", "A3" ],
  [ 1.1, 2.2, 3.3],
  [ 4.4, 5.5, 6.6] ]

到目前为止,我只有这些

library(rjson)
library(sqldf)
library(RSQLite)

convert = function (infile,outfile,name = "test"){
  data = fromJSON(file = infile)
  cols = length(data$header) #data[1]
  rows = length(data$data) #data[2]
  temp = matrix(NA, rows, cols) #create an empty dataframe and populate it

  for (i in 1:rows){
    for (j in 1:cols){
      temp[i,j] = ((data$data)[[i]])[[j]]
    }
  }

  #Save data into the dataframe
  temp = as.data.frame(temp)
  colnames(temp) = data$header

  #Save to sqlite
  db = dbConnect(SQLite(), dbname = outfile)
  dbWriteTable(conn = db, name = name, value = result, row.names = FALSE, overwrite = TRUE)

}

infile 是包含列表的 JSON 文件。列表的第一项是指定列名的字符串列表。列表的后续项目是数值列表。 outfile 是一个 SQLite 数据库,其中一个表表示 infile 中的数据,其中包含 3 列 A1 A2 A3。

【问题讨论】:

  • 你有什么问题?
  • @krlmlr 我想将该 JSON 文件转换为代表该数据的表格
  • 如何正确索引它?”的字面答案是:并非所有表都需要索引。该数据可能是 JSON values,但 keys 在哪里?

标签: r json sqlite rsqlite rjson


【解决方案1】:

从 JSON 转换为帧比您所拥有的要简单一些:

infile <- '
[ [ "A1", "A2", "A3" ],
  [ 1.1, 2.2, 3.3],
  [ 4.4, 5.5, 6.6] ]'

convert <- function(infile, outfile, name = "test") {
  dat <- jsonlite::fromJSON(infile)
  colnames(dat) <- dat[1,]
  dat <- as.data.frame(dat[-1,], stringsAsFactors = FALSE)
  con <- DBI::dbConnect(RSQLite::SQLite(), outfile)
  on.exit({ DBI::dbDisconnect(con) }, add = TRUE)
  DBI::dbWriteTable(con, name, dat, row.names = FALSE, overwrite = TRUE)
  return(dat)
}
convert(infile, "~/Downloads/quux.sqlite")
#    A1  A2  A3
# 1 1.1 2.2 3.3
# 2 4.4 5.5 6.6

con <- DBI::dbConnect(RSQLite::SQLite(), "~/Downloads/quux.sqlite")
str(DBI::dbGetQuery(con, "select * from test"))
# 'data.frame': 2 obs. of  3 variables:
#  $ A1: chr  "1.1" "4.4"
#  $ A2: chr  "2.2" "5.5"
#  $ A3: chr  "3.3" "6.6"

(我做了str 来证明它是按字面意思插入的;如果您需要转换为numeric,这是另一个简单的步骤。)

我为此使用了jsonlite,我相信(未经验证)它与rjson 的工作方式类似。

【讨论】:

  • warmsoda,这对你有用吗?如果是这样,请accept it。如果没有,edit 你的问题会提供更多信息来解释什么不起作用。请不要让您的问题悬而未决。
猜你喜欢
  • 2018-07-17
  • 2016-10-20
  • 2017-09-23
  • 2018-03-06
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多