Home > Enterprise >  Create Json from list in R with brackets
Create Json from list in R with brackets

Time:11-22

I am trying to create a JSON string to send in a POST request from an API (CTUIT's swagger API for restaurants).

# Load packages ----------------------------------------------
library(tidyverse)
library(httr)
library(jsonlite)

I make a nested list in R that I want to convert to JSON and use jsonlite::toJSON() to build the JSON string:

# Nested list
my_list <- 
  list(grouping = 2,
       locationID = 4,
       metricID = 1,
       startDate = '2021-10-31',
       endDate = '2021-10-31',
       filters = list(
                      id = 1, 
                      value = 6)
        ) 

# Convert the list to JSON
my_JSON <- jsonlite::toJSON(my_list, 
                            auto_unbox = TRUE, 
                            pretty = TRUE)


my_JSON

Here is the result:

{
  "grouping": 2,
  "locationID": 4,
  "metricID": 1,
  "startDate": "2021-10-31",
  "endDate": "2021-10-31",
  "filters": {
    "id": 1,
    "value": 6
  }
} 

What I need to figure out how to do is add square brackets [] around the "filters" element to match the API documentation. From the API instructions what this needs to look like is:

[
  {
    "grouping": 2,
    "locationID": 4,
    "metricID": 1,
    "startDate": "2021-10-31",
    "endDate": "2021-10-31",
    "filters": [
      {
        "id": 1,
        "value": [
          6
        ]
      }
    ]
   }
 ]

Is this possible with the jsonlite package?

I'm not sure the terminology for the square brackets, but I can easily add them on either side of the complete JSON string using paste0(). I'm trying to figure out how to get the square brackets for the inner elements of the JSON. Specifically the the nested "filters" element.

thanks

CodePudding user response:

Pretty straightforward:

jsonlite::toJSON(
    list(
        c(
            list(
                "grouping" = 2,
                "locationID" = 4,
                "metricID" = 1,
                "startDate" = "2021-10-31",
                "endDate" = "2021-10-31",
                "filters" = list(
                    list(
                        "id" = 1,
                        "value" = list(6)
                    )
                 
                )
            )
        )
    ), 
    pretty = TRUE,
    auto_unbox = TRUE
)

Which leads to:

[
  {
    "grouping": 2,
    "locationID": 4,
    "metricID": 1,
    "startDate": "2021-10-31",
    "endDate": "2021-10-31",
    "filters": [
      {
        "id": 1,
        "value": [
          6
        ]
      }
    ]
  }
] 
  • Related