如何使用 R 将 json 对象推入数组

How to push a json object into array using R

我尝试了几种技术将 json 对象推入数组并以与以下示例相同的格式保存,但没有成功。

有人有解决方案吗?

谢谢

编辑:

我找到了解决方案。

library(jsonlite)

#Set an empty list
list1 <- vector(mode = 'list', length = 2)

# data example
json_data <- list(object1 = list(birthday = '2000-02-14', Age = '20'), 
              object2 = list(Candidate_Number = '1999283', first_attempt = TRUE), 
              object3 = list(name = 'John E.', result = list(), study_hours = 150, GPA = 3.8, exam_infos = list(cost = 800, location = 'F3C6V9', past_exams = list(list(exam_name = 'Science', score = 'passed'), list(exam_name = 'Geometric', score = 'passed')))), 
              object4 = list(study_manual_used = 'Physics Theory', version_found = list(Digital = '1999-01-01', Paper = '1999-01-01')))

# append data into json
for(i in length(list1)){

  list1[[i]] <- json_data

}

# Write to json on his home
write(toJSON(list1, auto_unbox = TRUE, pretty = TRUE), file.path(Sys.getenv()['USERPROFILE'], 'file.json'))

要将对象另存为 JSON,您可以使用包 rjson

library("rjson")

# example data
list1 <- list()
list1[[1]] <- c(created_at="1910-02-03", id="212", field="1")
list1[[2]] <- c(created_at="1910-01-02", id="218", field="3")

# to json
toJSON(list1)

write(toJSON(list1), "file.json")

如果问题是您创建了 data.frame 并且需要将其恢复到 json。您必须按行将其列为:

# example data
dta <- as.data.frame(rbind(c(created_at="1910-02-03", id="212", field="1"), c(created_at="1910-01-02", id="218", field="3")))

# to json
toJSON(list(dta[1,],dta[2,]))