I wanted to make a yaml file from a python dict. But when I convert a regex string, the single quotes appears.
I want:
quickSearch:
type: string
maxLength: 250
pattern: [a-zA-Z0-9.\-_\u4e00-\u9fa5]+
but the result looks like:
quickSearch:
type: string
maxLength: 250
pattern: '[a-zA-Z0-9.\-_\u4e00-\u9fa5]+'
this is my code:
from ruamel.yaml import YAML
yaml = YAML()
param_dict = {
"quickSearch": {
"type": "string",
"maxLength": 250,
"pattern": "",
}
}
pattern = "[a-zA-Z0-9.\-_\\u4e00-\\u9fa5]+"
param_dict["quickSearch"]["pattern"] = pattern
with open("config.yaml", 'w', encoding='utf-8-sig') as f:
yaml.dump(param_dict, f)
How to represent all string without single quotes.
In YAML you cannot represent all possible strings without quotes, I am not sure where you get that misconceptions.
The opening square bracket is a special character denoting the beginning of a flow-style sequence ( i.e. one of the two possible representations of a Python list
in YAML).
Since your strings starts with a square bracket, if it would be dumped without it, it would not load back correctly, or in this case cause a loading error.
You should not worry about the quotes, any valid YAML parser will just remove them when loading back the string.