Handling NaN when using fromJSON in R
Asked Answered
S

2

8

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?

Shockheaded answered 12/8, 2015 at 2:24 Comment(4)
What is your command?Marden
have you tried jsonlite instead?Contumelious
I had the same issue however jsonlite didn't work for me but RJSONIO did.Breakable
#38493818Mauricio
I
2

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

Illfavored answered 20/4, 2020 at 21:6 Comment(0)
M
1

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.

Mooney answered 9/6, 2016 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.