Search code examples
jsonrhighchartsxtsr-highcharter

How to convert xts object in JSON in R?


I would like to convert an xts object which has the class Date into JSON with jsonlite::toJSON but it returns an error saying No method asJSON S3 class: zoo.

My objective is to have a JSON file that can be handled by highcharts.js library, so I'm trying to have severals arrays [unixtime, value], something like this :

[[1489363200, -0.01766174], [1489968000, 0.00000021], [1490572800, 0.00000098]]

This is my xts object :

> obj
             values
2017-03-13 -0.01766174
2017-03-20  0.00000021
2017-03-27  0.00000098

The documentation of toJSON mention a Date option that is used to encode Date objects: must be one of 'ISO8601' or 'epoch', but for some reason there is the same error.

> data <- toJSON(obj, dataframe = "values", Date="epoch")
Error: No method asJSON S3 class: zoo

If I convert the xts into a dataframe or a matrix I can export in JSON but the format is no appropriate for highcharts.js :

[-0.0177,"2017-03-13"],[0,"2017-03-20"],[0,"2017-03-27"]]

Is there a possibility to export an xts object in a JSON by keeping the time serie ?

Thank you,


Solution

  • One way to do it would be do it manually. The main steps are:

    1. Transform the xts to a data frame object
    2. Then transform the date object to numeric using the datetime_to_timestamp from the highcharter package.
    3. The use toJSON,


    library(xts)
    library(highcharter)
    library(jsonlite)
    data(sample_matrix)
    
    obj <- as.xts(head(sample_matrix[, 1], 3), descr = "my new xts object")
    obj
    #>                [,1]
    #> 2007-01-02 50.03978
    #> 2007-01-03 50.23050
    #> 2007-01-04 50.42096
    
    df <- data.frame(time = time(obj), values = as.vector(obj))
    df
    #>         time   values
    #> 1 2007-01-02 50.03978
    #> 2 2007-01-03 50.23050
    #> 3 2007-01-04 50.42096
    
    df$time <- datetime_to_timestamp(df$time)
    df
    #>           time   values
    #> 1 1.167707e+12 50.03978
    #> 2 1.167793e+12 50.23050
    #> 3 1.167880e+12 50.42096
    
    toJSON(as.matrix(df))
    #> [[1167706800000,50.0398],[1167793200000,50.2305],[1167879600000,50.421]]