I need to dynamically make a call to an API using the following format:
auth_secret <- paste0("Bearer ", secret)
headers = c(
`Authorization` = auth_secret,
`Notion-Version` = '2022-02-22',
`Content-Type` = 'application/json' )
res <- httr::PATCH(url = paste0('https://api.notion.com/v1/pages/', id),
httr::add_headers(.headers = headers),
body = payload,
encode = "json")
d <- httr::content(res)
This payload works:
payload <- "{\"properties\":{\"Project\":{\"relation\":[{\"id\":\"1d148a9e-783d-47a7-b3e8-2d9c34210355\"}]}}}"
But if I want to create it dynamically, using a paste0 (so it is inside of a function), I get some backslashes added before and after:
payload <- paste0('"{\"properties\":{\"',property_name,'\":{\"relation\":[{\"id\":\"',value,'\"}]}}}"')
print(payload)
"\"{\"properties\":{\"|AK^\":{\"relation\":[{\"id\":\"8cb9519e72ca4bbe9e0448807acb8e10\"}]}}}\""
I presume this is due to some weird escape character being added but have run out of ideas. I've added two \ and have gotten same issue. Call fails as JSON is not passed correctly. Is there a workaround?
CodePudding user response:
This is obviously something to do with the fact that paste0
is escaping even the double quotes you do not want to escape.
No doubt someone is aware of the details. However, when I get weird stuff with paste0
, I just use sprintf
, which seems to work in this case:
property_name = "Projects"
value = "1d148a9e-783d-47a7-b3e8-2d9c34210355"
payload <- sprintf(
"{\"properties\":{\"%s\":{\"relation\":[{\"id\":\"%s\"}]}}}",
property_name, value
)
print(payload)
# [1] "{\"properties\":{\"Projects\":{\"relation\":[{\"id\":\"1d148a9e-783d-47a7-b3e8-2d9c34210355\"}]}}}"