Reputation: 59
Let's say I have the following data....
areaId <- "abc123"
time <- format( seq.POSIXt(as.POSIXct(Sys.Date()), as.POSIXct(Sys.Date()+1), by = "5 min"),"%Y-%m-%d %H:%M:%S", tz="GMT")
value <- 10
df <- data.frame(areaId, time, value)
Giving output
$ areaId <chr> "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc123", "abc12…
$ time <chr> "2022-01-30 00:00:00", "2022-01-30 00:05:00", "2022-01-30 00:10:00", "2022-01-30 00:15:00", "2022-01-30 00:20:00", "…
$ value <dbl> 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, …
How can I convert into a JSON file that looks like this so I can POST to an API... everything I've tried so far gives me 3 individual arrays rather than 1.
{
"nameofdata": [
{
"areaId": "abc123",
"time": "2022-01-30T00:00:00Z",
"value": 0,
},
{
"areaId": "abc123",
"time": "2022-01-30T00:05:00Z",
"value": 0,
},
{
"areaId": "abc123",
"time": "2022-01-30T00:10:00Z",
"value": 0,
},
...
]
}
Many thanks for any assistance.
Upvotes: 1
Views: 23
Reputation: 11016
You can do:
library(jsonlite)
toJSON(list(nameofdata = df), pretty = TRUE)
which gives:
{
"nameofdata": [
{
"areaId": "abc123",
"time": "2022-01-30 00:00:00",
"value": 10
},
{
"areaId": "abc123",
"time": "2022-01-30 00:05:00",
"value": 10
},
{
"areaId": "abc123",
"time": "2022-01-30 00:10:00",
"value": 10
}
…
]
}
Upvotes: 1