LRD
LRD

Reputation: 361

write NULL in JSON object from R

I'm writing a JSON object from R where one of the values is null. But I cannot figure out how to write it in R so that in JSON appears as: null and not "null" nor {}.

Here is what I have in R:

id <- "S_0001"
count <- NULL
o <- list("id"=id, "count"=count)
toJSON(o, pretty=TRUE)

But this gives me the following JSON:

 {
  "id": ["S_0001"],
  "count": {}
 } 

And I need to get:

 {
   "id": ["S_0001"],
   "count": null
 }  

I tried unlist(NULL), or unbox("null"), etc. but with no luck. I've seen several posts on how to retrieve a null value from JSON to R, but not the inverse.

How could I achieve this?

Upvotes: 0

Views: 1313

Answers (2)

vladli
vladli

Reputation: 1573

If you have a data.frame and stumbled on this post: Use similar approach as @Stephane, but with na="null". Without it the column would not appear if it previously had NA as value:

> myDF = data.frame(a = c(1, NA), b = c(NA, 'c'))
> myDF
   a    b
1  1 <NA>
2 NA    c
> toJSON(myDF, na="null", pretty=TRUE)
[
  {
    "a": 1,
    "b": null
  },
  {
    "a": null,
    "b": "c"
  }
] 
> toJSON(myDF, pretty=TRUE)
[
  {
    "a": 1
  },
  {
    "b": "c"
  }
] 

Upvotes: 0

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84659

You have to use the null option:

> toJSON(o, null="null", pretty=TRUE)
{
  "id": ["S_0001"],
  "count": null
} 

Upvotes: 6

Related Questions