R replace quoted values in YAML

Solution 1:

workaround

Although this might be difficult for more complex YAML file outputs, there is a workaround to the apparent inability of the yaml package to force quotations, as explored below. We can use regex to match, in this example, any non-quoted continuous group of letters or numbers and force quotations around it.

library(stringr)

test <- list("a"=list("b"=123L, "c"="rabbitmq", d = "Yes"))
test_yaml <- as.yaml(test)
test_yaml
#> [1] "a:\n  b: 123\n  c: rabbitmq\n  d: 'Yes'\n"

We can see here that we might want to quote 123 and rabbitmq (Yes is already in quotes).

test_yaml <- str_replace_all(test_yaml, "(?<=:\\s)([a-zA-Z0-9]*?)(?=\n)", "'\\1'")
test_yaml
#> [1] "a:\n  b: '123'\n  c: 'rabbitmq'\n  d: 'Yes'\n"

And then write this to your YAML file.

write_yaml(test_yaml, "/Users/caldwellst/Desktop/test.yaml")

We then get your, I'm assuming, desired output.

  a:
    b: '123'
    c: 'rabbitmq'
    d: 'Yes'

yaml package

write_yaml is using strings to force a quote, because otherwise 123 would be interpreted as numeric. You don't need quotes for rabbitmq because it will automatically be interpreted as a string. If you actually want 123 to be interpreted as numeric, just pass it as such.

test <- list("a"=list("b"=123, "c"="rabbitmq"))
as.yaml(test)
write_yaml(test, "test.yaml")

Then you get:

a:
  b: 123.0 # pass b as 123L to force integer output
  c: rabbitmq

Per the documentation of write_yaml:

Character vectors that have a class of ‘verbatim’ will not be quoted in the output YAML document except when the YAML specification requires it

Although that is a way to force certain values to be output without quotes, there appears to be no easy way to force quoting of values. I've tried with passing unicode = T and explicit quotes in the string, but they are removed. As well, I tried to trick the system by passing in various handlers to manipulate class (and remove verbatim if it was there. However, none seem to work. As the source code is in C, not able to get something working with the write_yaml function.

There's a detailed answer about the YAML syntax and quoting in general in this great SO post.