Why does R add an extra set of square brackets around each list within my JSON object?

46 Views Asked by At

I'm trying to use httr2 to POST an application/JSON request. However, the server errs apparently because I can't seem to avoid slurping into the JSON object the brackets delineating each R character vector for each individual list item. How can I instead output a JSON object with one named field, the value of which is one list, containing three lists, each of which contain three strings?

library(httr2)
library(jsonlite)


# json object
# Data is a list of lists of entities
Data <- list(
  list('alfa', 'bravo', 'charlie'),
  list('charlie', 'delta', 'echo'), 
  list('echo', 'golf', 'foxtrot')
)

# Create a named list containing the above list so we can end up with a JSON object with one named field containing the above list
named_list <- list(Entities = Data)

# Convert the named list to a JSON object
json_object <- toJSON(named_list, pretty = TRUE)

# Print the JSON object
cat(json_object)

# Make an httr2 request object
req <- request(##URL goes here###)

# Add headers by piping req_headers()'s output to req
req <- req %>% req_headers("Accept" = "application/json")

# Add the json data
req <- req %>% req_body_json(json_object)

# Dry Run!
req %>% req_dry_run()

# Perform the request
resp <- req_perform(req)

print(resp_raw(resp))

Both cat(json_object) and the dry run show my JSON object is this:

{
    "Entities": [
        [
            ["alfa"],
            ["bravo"],
            ["charlie]"
        ],
        [
            ["charlie"],
            ["delta"],
            ["echo"]
        ],
        [
            ["echo"],
            ["golf"],
            ["foxtrot"]
        ]
    ]
}

But my JSON object should be this:

{
    "Entities": [
        [
            "alfa",
            "bravo",
            "charlie"
        ],
        [
            "charlie",
            "delta",
            "echo"
        ],
        [
            "echo",
            "golf",
            "foxtrot"
        ]
    ]
}
1

There are 1 best solutions below

0
fpt On

Dave2e's suggestion to use toJSON's auto_unbox parameter yielded the results I was looking for. Thank you!