将R中的日期转换为JSON格式

时间:2016-03-26 11:07:46

标签: r datetime rjson

我想将日期转换为JSON格式。 R all.elasticities data.frame如下所示:

 PREVIOUS_START_DATE PREVIOUS_PRICE PREVIOUS_QUANTITY PRE_No_OF_WEEKS CURRENT_START_DATE
         2015-12-20           2.79           20680.5               2         2015-12-20         
         2016-01-17           2.29           21049.5               4         2016-01-17         
         2016-01-31           1.69           24689.5               2         2016-01-31      

我正在使用,

 x <- toJSON(unname(split(all.elasticities, 1:nrow(all.elasticities))))

我的输出为,

"[{\"PREVIOUS_START_DATE\":16789,\"PREVIOUS_PRICE\":2.79,\"PREVIOUS_QUANTITY\":20680.5,\"PRE_No_OF_WEEKS\":2,\"CURRENT_START_DATE\":16789},{\"PREVIOUS_START_DATE\":16817,\"PREVIOUS_PRICE\":2.29,\"PREVIOUS_QUANTITY\":21049.5,\"PRE_No_OF_WEEKS\":4,\"CURRENT_START_DATE\":16817},{\"PREVIOUS_START_DATE\":16831,\"PREVIOUS_PRICE\":1.69,\"PREVIOUS_QUANTITY\":24689.5,\"PRE_No_OF_WEEKS\":2,\"CURRENT_START_DATE\":16831}]"

日期正在转换为数字。我想保留日期格式。

2 个答案:

答案 0 :(得分:1)

library(jsonlite)适用于日期格式,也无需拆分data.frame。

 str(all.elasticities)
'data.frame':   3 obs. of  5 variables:
 $ PREVIOUS_START_DATE: Date, format: "2015-12-20" "2016-01-17" "2016-01-31"
 $ PREVIOUS_PRICE     : num  2.79 2.29 1.69
 $ PREVIOUS_QUANTITY  : num  20680 21050 24690
 $ PRE_No_OF_WEEKS    : int  2 4 2
 $ CURRENT_START_DATE : Date, format: "2015-12-20" "2016-01-17" "2016-01-31"


> jsonlite::toJSON(all.elasticities, pretty=T)
[
  {
    "PREVIOUS_START_DATE": "2015-12-20",
    "PREVIOUS_PRICE": 2.79,
    "PREVIOUS_QUANTITY": 20680.5,
    "PRE_No_OF_WEEKS": 2,
    "CURRENT_START_DATE": "2015-12-20"
  },
  {
    "PREVIOUS_START_DATE": "2016-01-17",
    "PREVIOUS_PRICE": 2.29,
    "PREVIOUS_QUANTITY": 21049.5,
    "PRE_No_OF_WEEKS": 4,
    "CURRENT_START_DATE": "2016-01-17"
  },
  {
    "PREVIOUS_START_DATE": "2016-01-31",
    "PREVIOUS_PRICE": 1.69,
    "PREVIOUS_QUANTITY": 24689.5,
    "PRE_No_OF_WEEKS": 2,
    "CURRENT_START_DATE": "2016-01-31"
  }
] 

答案 1 :(得分:0)

正如评论中所提到的,您需要先将日期转换为字符:

x = as.Date("2016-01-01")
RJSONIO::toJSON(as.character(x))

当您不转换为字符时,该值会更改为数字,表示自1970年以来的天数,例如

as.numeric(x)
as.numeric(x)/365