【发布时间】: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