3

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!

2
  • stackoverflow.com/questions/31955051/… I found this post may be it will help Commented Jul 21, 2016 at 1:23
  • which package is your fromJSON from there are a few of them in CRAN Commented Jul 21, 2016 at 1:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help. I am using 'rjson' package.
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
So, why didn't you try one of the two solutions in this answer?
I tried the RJSONIO package and it works. The reading output of JSON is named numeric array. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.