When getting data via an API, I get the following format of dates back in JSON "/Date(1386201600000)/". I tried rvest, httr, jsonlite, and rjson, but they all return this date format. To solve this I wrote the function convert_JSON_Date to transform this data into readable dates. This works and returns the correct date.
Using the function over the whole date column I get a warning message that NAs were introduced by coercion. I found out that this has something to do with the length of the json date format. Some of them are 20 characters and long some are 21. In my total dataset there are even more different lenghts. When I put the data through the function for each length separately, everything works fine.
I have no idea why the coercion errors occur. I was wondering if someone has an explanation of why this is happening.
# Example data
t <- c("/Date(1184889600000)/", "/Date(1377648000000)/", "/Date(1386201600000)/",
"/Date(1099353600000)/", "/Date(1403222400000)/", "/Date(1052092800000)/",
"/Date(1324425600000)/", "/Date(1115942400000)/", "/Date(1343260800000)/",
"/Date(940377600000)/", "/Date(1438819200000)/", "/Date(975715200000)/",
"/Date(1125446400000)/", "/Date(1194566400000)/", "/Date(1331856000000)/",
"/Date(1396569600000)/", "/Date(1346803200000)/", "/Date(1438560000000)/",
"/Date(950832000000)/", "/Date(1380326400000)/", "/Date(1432771200000)/",
"/Date(1436572800000)/", "/Date(1376438400000)/", "/Date(1428537600000)/",
"/Date(869788800000)/", "/Date(1343001600000)/", "/Date(1382486400000)/",
"/Date(1259539200000)/", "/Date(1427500800000)/", "/Date(1421971200000)/")
# converter for json dates.
convert_JSON_Date <- function(Input_String){
start <- stringi::stri_locate(Input_String, regex = "\\(")[1,1]
end <- stringi::stri_locate(Input_String, regex = "\\)")[1,1]
# shift 1 position from the start and end to get the string between the parentheses
JSON_Date <- stringi::stri_sub(Input_String, start+1, end-1)
# Not interested in time element. This is the time the data was uploaded to server
JSON_Date <- as.Date(structure(as.numeric(JSON_Date)/1000, class = c("POSIXct", "POSIXt")))
return(JSON_Date)
}
# NAs introduced by coercion
convert_JSON_Date(t)
# separetely it works
convert_JSON_Date(t[nchar(t) == 20])
# separetely it works
convert_JSON_Date(t[nchar(t) == 21])