c00kiemonster
c00kiemonster

Reputation: 23361

How can I make rjson's fromJSON method convert JSON NULLs to R NAs?

I could of course solve this downstream in R, but I think that would be messier compared to just get rjson to do it for me somehow. Can it be done?

Upvotes: 5

Views: 1347

Answers (2)

Iterator
Iterator

Reputation: 20560

Two ideas:

  1. Take a look at RJSONIO instead, and use its fromJSON. The argument to look for is nullValue, which you can set to be NA. I switched from rjson to RJSONIO a long time ago, after doing some speed tests and it also produces somewhat more readable JSON.
  2. Consider reading in the text as a string, and replace 'null' with 'NA' using gsub(). This isn't particularly robust if you aren't familiar with regular expressions (if "null" is part of a bit of text, you could end up dropping it, so it's important to be careful).

Upvotes: 4

joran
joran

Reputation: 173677

It looks to me like fromJSON in the rjson package does all its work in C code, so my guess is that there isn't an easy way to alter its behavior without altering the C code itself. You're probably better off doing the conversion in R.

You could simply wrap fromJSON in your own function that replaces NULL to NA. That would prevent your code itself from getting too terribly messy.

Upvotes: 0

Related Questions