看下,这次对了。
[Ruby on Rails] 纯文本查看 复制代码 # 安装 jsonlite 包(如果尚未安装)
if (!requireNamespace("jsonlite", quietly = TRUE)) {
install.packages("jsonlite")
}
# 加载 jsonlite 包
library(jsonlite)
# 读取 JSON 文件内容
json_content <- readLines("FR-parliament.json", encoding = "UTF-8")
# 尝试解析 JSON 文件
tryCatch({
data <- jsonlite::fromJSON(txt = "FR-parliament.json", simplifyVector = FALSE)
data <- data$trends$kalmanSmooth
# 获取所有政党名称
parties <- c("date", "DIVLeft", "DIVRight", "DLF", "EELV", "FI", "LONPA", "LR", "LREM", "MoDem", "NUPES", "PCF", "PS", "REC", "RN")
# 创建 CSV 表头
header <- parties
# 准备 CSV 数据
csv_data <- lapply(data, function(entry) {
row_data <- c()
for (party in parties) {
if (party == "date") {
row_data <- c(row_data, entry[[party]])
} else {
if (party %in% names(entry$parties)) {
row_data <- c(row_data, entry$parties[[party]])
} else {
row_data <- c(row_data, "NA")
}
}
}
return(row_data)
})
# 转换为数据框并设置列名
csv_data_df <- do.call(rbind, csv_data)
colnames(csv_data_df) <- header
# 保存为 CSV 文件
write.csv(csv_data_df, file = "FR-ep.json.csv", row.names = FALSE, fileEncoding = "UTF-8")
print("Data has been saved to FR-ep.json.csv")
}, error = function(e) {
print("An error occurred while processing the JSON file:")
print(e)
})
|