Jsonlite - No longer accepting path?

Hi,

I have a small snippet of code I used to convert JSON files to CSV. This was working until a 3-4 weeks ago.

library(tidyverse)
library(jsonlite)

x <- fromJSON(paste("D:\\FOLDER1\\FOLDER2\\FOLDER3\\FOLDER4\\FOLDER5\\FOLDER6\\FOLDER7\\JSON_FILE.json",
              sep = ""),
              flatten = TRUE)
x <- as.data.frame(x)
readr::write_csv(x,paste("D:\\FOLDER1\\FOLDER2\\FOLDER3\\FOLDER4\\FOLDER5\\FOLDER6\\FOLDER7\\JSON_CONVERTED_TO_CSV.csv",
                         sep = ""))

But now, while using this code I've used several times before, is giving me the following error:

Error: lexical error: invalid char in json text.
                                       D:\FOLDER1\FOLDER2\FOLDER3
                     (right here) ------^

Which appears to be complaining about the ":" (colon) that comes after the drive the folders are located.

Any clues on how to point the file path for the JSON so I can convert it to CSV. I'm unsure what has changed that is causing the above error that did not happen before.

Any feedback would be greatly appreciated.

Thank you for your time.
Best regards,
TB.

My impression is that this error appears when the file does not exist:

library(jsonlite)

toJSON(data.frame(x=0)) |>
  writeLines("test.json")

fromJSON("test.json")
#>   x
#> 1 0

fromJSON("oh_no.json")
#> Error: lexical error: invalid char in json text.
#>                                        oh_no.json
#>                      (right here) ------^

Created on 2023-04-03 by the reprex package (v2.0.1)

(and if you give an absolute path, the ^ still points to the second character, which is :)

And you can actually see how it works looking at the source code of fromJSON(), here is a simplified version:

if (file.exists(txt)) {
  txt <- file(txt)
}
parse_and_simplify(txt = txt, ...)

So, the function tries to find a file at txt, if there is no such file, it's assuming you're directly giving the JSON as text and tries to parse it. So if you give a path to a file that doesn't exist, it'll try to parse that path and fail, because it's not JSON.

1 Like

Yeah, you were correct.

Adding insult to injury, POSTMAN was NOT saving the JSON as a JSON, just as "File". Once I fixed the extension, it all fell in place. This was a bizarre unexpected behavior from Postman that took me off track.

Thanks for the insight.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.