2

I have a problem to read json file by using jsonlite::fromJSON. It shows error message as below:

Error in fromJSON(file = jsonfile.names[1]) : unexpected character 'N'.

It is a problem with NaN values in the json file. If I remove or change all the NaN to strings or numbers, fromJSON works just fine.

A sample of my data follows below:

{"name": NaN,
"unit_price": 130848,
"amount": 11,
"up_to_data_sales": 45725}

Is there any solution to solve this problem without manually changing the json file?

Thanks in advance!

rodolfoksveiga
  • 1,181
  • 4
  • 17
gchen
  • 21
  • 1
  • 3

1 Answers1

5

That's not technically JSON. It's JavaScript.

We can use the V8 package here:

library(V8)

jsraw <- '{"name": NaN, "unit_price": 130848, "amount": 11, "up_to_data_sales": 45725}'

ctx <- v8()
ctx$assign("dat", JS(jsraw))
ctx$get("dat")

## $name
## NULL
## 
## $unit_price
## [1] 130848
## 
## $amount
## [1] 11
## 
## $up_to_data_sales
## [1] 45725

You can obtain similar results with RJSONIO::fromJSON(jsraw) (hence me asking which JSON package you were using).

But, this is a toy example, so if we had more info from you we could probably come up with a more general solution.

Also, hand-editing data is generally a really, really bad idea.

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • Thanks for the help. I am using 'rjson' package. – gchen Jul 21 '16 at 03:50
  • I tried both 'rjson' and 'jsonlite' package. The 'fromJSON' function in both package is not compatible with the value of 'NaN' of the item. After i manually change the value of 'NaN' to 0 of these item, the function works fine. I don't know whether there is some decent solution on this. Thanks – gchen Jul 21 '16 at 07:00
  • So, why didn't you try one of the two solutions in this answer? – hrbrmstr Jul 21 '16 at 10:13
  • I tried the RJSONIO package and it works. The reading output of JSON is named numeric array. Thanks. – gchen Jul 21 '16 at 18:45