2

I am having trouble with converting a data structure to JSON without representing numerics in scientific notation.

library(rjson)

options(scipen=1000)

toJSON(c(1200000000, 400000))

# [1] "[1.2e+08,400000]"

How can I make it output "[1200000000,400000]" ?

zx8754
  • 52,746
  • 12
  • 114
  • 209
WYi
  • 1,565
  • 2
  • 16
  • 16
  • I can't reproduce this behavior. Are you using an old version of R or rjson? – joran May 30 '12 at 17:09
  • on R 2.15.0 and rjson 0.2.8 my output matches WYi's. – Justin May 30 '12 at 17:33
  • Possible duplicate of [How to disable scientific notation in R?](https://stackoverflow.com/questions/5352099/how-to-disable-scientific-notation-in-r) – amonk Jul 18 '17 at 09:04

1 Answers1

1

Update from 2018: use jsonlite like everyone nowadays:

> toJSON(c(1200000000, 400000))
[1200000000,400000] 

Original answer from 2012:

I would also suggest to transform the numbers to strings before passing to toJSON just as @gauden wrote above. But if you would not do that try RJSONIO package (which is faster anyway) which has a digits option:

>  toJSON(c(1200000000, 400000), digits = 10)
[1] "[  1200000000,      400000 ]"

But this would result in some extra whitespace as you can see.


Update: it seems that @gauden deleted his answer so adding some details

You might call e.g. format before transforming the "numbers" to JSON like:

> toJSON(format(c(1200000000, 400000), scientific = FALSE, trim = TRUE))
[1] "[\"1200000000\",\"400000\"]"
daroczig
  • 28,004
  • 7
  • 90
  • 124
  • Thanks @daroczig. But I have a much larger object to convert to JSON, so manually formatting each numeric isn't scalable in my case. – WYi May 31 '12 at 15:56
  • You can still use `RJSONIO::toJSON` with `digits` parameter, but I am really not sure why is it a bad idea to run `format` (which is vectorized) on a large object. E.g.: `format(mtcars, decimal.mark=',')` – daroczig May 31 '12 at 16:04
  • RJSONIO still output scientific notation. Format converts numbers to strings, not ideal. – Feng Jiang May 28 '18 at 21:32
  • @daroczig it does not work when you do this: toJSON(c(0.00007757)) – Feng Jiang May 29 '18 at 14:24
  • @Jfly if you need more significant digits, set the related argument of `toJSON` – daroczig May 29 '18 at 17:55
  • @daroczig You can try jsonlite::toJSON(c(0.00007757), digits = 20). It shows scientific notation. But it turns out jsonlite::toJSON(c(0.00007757), digits = 6) works. – Feng Jiang May 30 '18 at 19:01