0

I have tried several technics to push json object into an array and to save in the same format of the below example, but without success.

Is anyone has a solution to do it in R ?

Thanks you

EDIT :

I found the solution.

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'))
John E.
  • 137
  • 2
  • 10
  • 2
    Please don't use images for data. I don't undertsand the question. Please give an example of the input and the expected output. – Stéphane Laurent Feb 14 '20 at 14:31
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Don't put data in images because we can't copy/paste the data to test that way. What are the techniques you tried? How did they fail exactly? – MrFlick Feb 14 '20 at 16:02
  • I agree with your comment. I will pay attention to these details for the next time. Meanwhile, I edited my post and write the solution. Thanks you – John E. Feb 14 '20 at 20:04

1 Answers1

0

To save object as JSON you can use package 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)

and

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

If the issue is that you created data.frame and need to make it back into json. You have to make it a list by row as:

# 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,]))
jyr
  • 690
  • 6
  • 20