首页 > 解决方案 > 从 CSV 到 json 格式的 .txt rstudio

问题描述

我是R的初学者。

我有一个 csv 文件:

key1 key2 key3 key4 key5 key6 

value value value value value  
value value value value value  
value value value value value 

etc.

我会将 CSV 文件转换为这种格式并将其保存在 .txt 文件中,这样我就可以在需要这种格式的服务器的批量上传中使用它:

{"key1": "value", "key2": "value", "key3": "value", "key4": "value", "key5": "value"}

{"key1": "value", "key2": "value", "key3": "value", "key4": "value", "key5": "value"}

{"key1": "value", "key2": "value", "key3": "value", "key4": "value", "key5": "value"}

这是我到目前为止在 Rstudio 中的内容:

#install packages
install.packages('jsonlite')


#libraries
library(readr)
library(jsonlite)


#import data
plantasia_menu_items <- read_csv("plantasia - menu_items.csv")
#View(plantasia_menu_items)

#to Json format 
inJSON <- toJSON(plantasia_menu_items)
table <- fromJSON(inJSON)
print(inJSON)

这会产生以下格式的数据,但我不知道如何在 JSON 中对其进行重构然后保存它:

{"key1": "value", "key2": "value", "key3": "value", "key4": "value", "key5": "value"} {"key1": "value", "key2": "value", "key3": "value", "key4": "value", "key5": "value"} {"key1": "value", "key2": "value", "key3": "value", "key4": "value", "key5": "value"}

它必须在新行上,以便服务器了解批量上传并创建新条目。现在卡了一段时间。关于如何将其重组为矩阵的任何想法?

标签: rjsoncsv

解决方案


这是我最终用来重新格式化数据的代码。但是,我不确定如何将其保存到 .txt 文件中。我无法将它放入数据框中,因为它不是向量。有任何想法吗?

#clean the working environment
rm(list=ls())

#set working directory, keep files organized
setwd("C:/Users/")

#
#install packages('readr'}
#install.packages('jsonlite')
#install.packages("stringr")
#install.packages("stringi")

#libraries
library(readr)
library(jsonlite)
library(stringr)
library(stringi)

#import data in csv format
data <- read_csv("test.csv")
#View(data)

#Convert the CSV to Json format and verify it worked by printing
inJSON <- toJSON(data)
print(inJSON)

#Finding the locations of the separators of each data entry. 
#This will allow us to determine to know where to begin and end the substring
# generating two tables indicating each location of patterns along the whole string
start_table <- data.frame(str_locate_all(inJSON, "key1"))
#start_table

stop_table <- data.frame(str_locate_all(inJSON, ","))
#selecting row 1, col 2.
#stop_table[1,2]

#defining the function that will restructure the data for bulk upload format
restrucJSON <- function(jsonformat){

  #prepping the loop 
  count <- str_count(jsonformat, "key1") #count the number of times the loop is going to run, or the number of database entries 
  a <- 1 #there is only one row per entry 
  b <- 6 #there are 6 columns in this data, so we take every 6th position of the commas

  #loop to print
  for (i in c(1:count)) { #using the count to tell the loop how many times to run
    x <- start_table[a,1]
    y <- stop_table[b,1]
    print(substr(jsonformat, x-2, y-1)) 
    a <- a+1 #
    b <- b+6 #start counting from the next 6th comma
  }

}

#try out the function with the inJSON object
export <- restrucJSON(inJSON)

推荐阅读