jsonlite
jsonlite copied to clipboard
fromJSON is.na check is incomplete
Thank you for your great contribution to the R world, I am using jsonlite on a regular basis and it is a great tool. Nevertheless, I found a minor issue in the error reporting of fromJSON, which is slightly confusing in my oppinion, and you may change this easily, if you agree:
The function fromJSON checks, if input is NA (jsonlite_1.5):
https://github.com/jeroen/jsonlite/blob/e5e61434790c39277f198f204f13d0da36e4095c/R/fromJSON.R#L86
This works, as long as the input is not NA. Usually, NA is logical, so the line above will treat the situation:
https://github.com/jeroen/jsonlite/blob/e5e61434790c39277f198f204f13d0da36e4095c/R/fromJSON.R#L81
However, if I call fromJSON with a NA which was casted to a character, it won't (error messages translated from German, may not be excatly the original terms):
> fromJSON(NA)
Error: Argument 'txt' must be a JSON string, URL or file.
> fromJSON(as.character(NA))
Error in if (is.character(txt) && length(txt) == 1 && nchar(txt, type = "bytes") < :
Missing value, where TRUE/FALSE expected
What I would expect, is the following behaviour:
> fromJSON(NA)
Error: Argument 'txt' must be a JSON string, URL or file.
> fromJSON(as.character(NA))
Error: Argument 'txt' must be a JSON string, URL or file.
So, you should amend https://github.com/jeroen/jsonlite/blob/e5e61434790c39277f198f204f13d0da36e4095c/R/fromJSON.R#L81 by a NA check, something like:
if (is.null(txt) || is.na(txt) || (!is.character(txt) && !inherits(txt, "connection"))) {
I also added is.null, since this causes similar confusing error messages.
Feel free to use my suggested code, if you like, I would be happy to have clearer error messages in future. Thank you again
Stephan
I just got bit by this again. I also realize I'm not sure I ever filed a PR on this commit from 1.5 years ago:
https://github.com/MichaelChirico/jsonlite/commit/7e41e303d3cccd6b982e69057f4c112f7817d80b
Getting this issue too.
I'm getting this too.
In my case the cause of the issue was a single invalid character (some Unicode issue I think) in the source data provided by an API, which httr2::resp_body_json() would fail to read without an error. (resp_body_json uses jsonlite I believe).