How to escape indicator characters (i.e. : or - ) in YAML

后端 未结 7 2169
醉话见心
醉话见心 2020-11-27 12:13

In a config file, I have a key to which I wish to assign a URL. The problem is that YAML interprets : and - characters as either creating mappings or lists, so it has a pro

相关标签:
7条回答
  • 2020-11-27 12:22

    What also works and is even nicer for long, multiline texts, is putting your text indented on the next line, after a pipe or greater-than sign:

    text: >
        Op dit plein stond het hoofdkantoor van de NIROM: Nederlands Indische 
        Radio Omroep
    

    A pipe preserves newlines, a gt-sign turns all the following lines into one long string.

    0 讨论(0)
  • 2020-11-27 12:22

    According to the YAML spec, neither the : nor the - should be a problem. : is only a key separator with a space after it, and - is only an array indicator at the start of a line with a space after it.

    But if your YAML implementation has a problem with it, you potentially have lots of options:

    - url: 'http://www.example-site.com/'
    - url: "http://www.example-site.com/"
    - url:
        http://www.example-site.com/
    - url: >-
        http://www.example-site.com/
    - url: |-
        http://www.example-site.com/
    

    There is explicitly no form of escaping possible in "plain style", however.

    0 讨论(0)
  • 2020-11-27 12:22

    Another way that works with the YAML parser used in Jekyll:

    title: My Life: A Memoir
    

    Colons not followed by spaces don't seem to bother Jekyll's YAML parser, on the other hand. Neither do dashes.

    0 讨论(0)
  • 2020-11-27 12:26

    Quotes:

    "url: http://www.example-site.com/"
    

    To clarify, I meant “quote the value” and originally thought the entire thing was the value. If http://www.example-site.com/ is the value, just quote it like so:

    url: "http://www.example-site.com/"
    
    0 讨论(0)
  • 2020-11-27 12:28

    If you're using @ConfigurationProperties with Spring Boot 2 to inject maps with keys that contain colons then you need an additional level of escaping using square brackets inside the quotes because spring only allows alphanumeric and '-' characters, stripping out the rest. Your new key would look like this:

    "[8.11.32.120:8000]": GoogleMapsKeyforThisDomain
    

    See this github issue for reference.

    0 讨论(0)
  • 2020-11-27 12:37

    Quotes, but I prefer them on the just the value:

    url: "http://www.example.com/"
    

    Putting them across the whole line looks like it might cause problems.

    0 讨论(0)
提交回复
热议问题