0

I am trying to read list of json files in my local folder. But the below code does not work. Can anyone help me in solving this

json_files <- list.files(pattern = "*.json")
for(i in length(json_files))
{
json_data3[[i]] <- fromJSON(paste(readLines[[i]],collapse = ""))
}
2
  • 1
    I think instead of readLines[[i]] you want readLines(json_files[[i]]). Commented Jan 17, 2020 at 11:07
  • 1
    What do you need the readLines for? fromJSON(json_files[i]) is how I usually read them in. Commented Jan 17, 2020 at 11:11

1 Answer 1

1

Im not sure, which json library you are using, but it looks like jsonlite:

library(jsonlite)

json_data <- lapply(list.files(pattern = "*.json"), read_json)
json_data2 <- lapply(list.files(pattern = "*.json"), fromJSON)

To preserve the names of your files as list entries you can do:

names(json_data) <- list.files(pattern= "*.json")
# OR
json_data3 <- sapply(list.files(pattern="*.json"),FUN = read_json,
                     simplify = FALSE,USE.NAMES = TRUE)
Sign up to request clarification or add additional context in comments.

2 Comments

Hi. thanks. It worked for me. Is it possible to have the file name in list ? right now i do not get from which file I have extracted the data
The lazy mans solution is names(json_data) <- list.files(pattern="*.json"), but i also edited the main post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.