R - JSON Structure for POST

Viewed 37

I've read everything i can find around create JSONs using toJSON(), but it's just not clicking. Any guidance would be greatly appreciated.

I am trying to create a JSON for a POST request to an API. I'm trying to create the following structure:

{
  "configuration": {
    "Id": 1,
    "OptionIds": [
            261,
            263,
            533122,
            228  
    ]
  },
  "length": 15000,
  "zip": "92691",
  "Date": "2019-09-11T15:46:31.354Z"
  }

Trying to break it down element by element I can begin to get close, but can never get to the final solution once attempt to combine everything.

For example.

v_opt_ids <- list(OptionsIds = c(261,
                                 263,
                                 533122,
                                 228))

cat(jsonlite::toJSON(v_opt_ids, pretty=T))

Produces:

{
  "OptionsIds": [261, 263, 533122, 228]
}

And while this is not exactly what i'm aiming for in that portion, when combined with additional elements.

config <- data.frame(
      vehicleId = c(444449),
      v_opt_ids)

cat(jsonlite::toJSON(list(configuration = config), pretty=T))

Things go awry pretty quickly..

{
  "configuration": [
    {
      "vehicleId": 444449,
      "OptionsIds": 261
    },
    {
      "vehicleId": 444449,
      "OptionsIds": 263
    },
    {
      "vehicleId": 444449,
      "OptionsIds": 533122
    },
    {
      "vehicleId": 444449,
      "OptionsIds": 228
    }
  ]
}

Any guidance would be greatly appreciated.

1 Answers

Use nested lists:

L <- list(
  configuration = list(
    Id = 1,
    OptionIds = c(261, 263, 533122, 228)
  ),
  length = 15000,
  zip = "92691",
  Date = "2019-09-11T15:46:31.354Z"
)

jsonlite::toJSON(L, pretty = TRUE, auto_unbox = TRUE)
# {
#   "configuration": {
#     "Id": 1,
#     "OptionIds": [261, 263, 533122, 228]
#   },
#   "length": 15000,
#   "zip": "92691",
#   "Date": "2019-09-11T15:46:31.354Z"
# } 

(pretty=TRUE is not required for the JSON, just using it to attempt to match your expected output. auto_unbox=TRUE ensures that one gets "Id":1 instead of "Id":[1], which is functionally identical for most things that consume json, some find it a preferable format.

Related