user2020282
user2020282

Reputation: 117

Handling NaN when using fromJSON in R

I'm trying to use the fromJSON function in R to read in a JSON file that was given to me, however this file has NaN in it and I can't read it in properly.

This is the error I get:

Error in feed_push_parser(buf) : 
  lexical error: invalid char in json text.

Anyone know how to read NaN values when reading in a json file into R?

Upvotes: 8

Views: 2794

Answers (2)

GameChanger
GameChanger

Reputation: 106

As referenced in the comments, RJSONIO can handle NaN. By default, the NaN values will be excluded. If you want to include the NaN values you can set the NaN values to NA via nullValue.

Example Code - Replacing NaN with NA

library(RJSONIO)

json_imported <- fromJSON(content,nullValue=NA)

The value for 'content 'is the JSON content. Via RJSONIO documentation, "This can be the name of a file or the content itself as a character string. We will add support for connections in the near future."

Upvotes: 2

user6397960
user6397960

Reputation: 53

I had similar problem. To resolve this, you can try one of the below as it worked for me. i) Open JSON file in np++ and replace any value with NaN with "NA" (quoted). Otherwise R misunderstands NaN as numeric value which is expected as "NA". By replacing NaN as "NA", R reads "NA" as character.

ii) convert the JSON file to csv and load the csv file in R using read.csv() command.

Upvotes: 1

Related Questions