jsonlite icon indicating copy to clipboard operation
jsonlite copied to clipboard

fromJSON is.na check is incomplete

Open struckma opened this issue 7 years ago • 3 comments

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

struckma avatar Nov 07 '17 14:11 struckma

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

MichaelChirico avatar Feb 23 '20 18:02 MichaelChirico

Getting this issue too.

kieran-mace avatar Apr 10 '20 00:04 kieran-mace

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).

francisbarton avatar Jul 29 '22 02:07 francisbarton