1

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.

1
  • What have you tried so far? Commented Jan 30, 2022 at 11:38

1 Answer 1

1

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
    }
…
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.