Following on from this question: JSON to YAML in Python : How to get correct string manipulation?
I’d like to have specific key names (regardless of nesting depth) always given a double-quote style. This is the starting point:
import sys
from ruamel.yaml import YAML
data = {
'simple': 'nonquoted',
'grouping': 'quoted',
'deep': {
'simple': 'nonquoted',
'grouping': 'quoted',
}
}
def test():
yaml = YAML()
yaml.default_flow_style = False
yaml.dump(data, sys.stdout)
test()
which currently gives:
simple: nonquoted
grouping: quoted
deep:
simple: nonquoted
grouping: quoted
Id like it to be:
simple: nonquoted
grouping: "quoted"
deep:
simple: nonquoted
grouping: "quoted"
I’ve looked at adding representers, but I got stuck. Can someone show me how?
I have Python 3.10.13 and ruamel.yaml 0.18.6.
Update: I’m able to do this by walking the tree, applying the ruamel
specific type DoubleQuotedScalarString
but maybe there is a way to do it on dump
?
# Function to preprocess in-place the dictionary to quote values for specific keys
def preprocess_dict_in_place(data, doubleQuoteKeys={}):
if isinstance(data, dict):
for key in list(data.keys()):
if key in doubleQuoteKeys:
data[key] = DoubleQuotedScalarString(data[key])
elif isinstance(data[key], dict):
preprocess_dict_in_place(data[key], doubleQuoteKeys)
elif isinstance(data[key], list):
for index in range(len(data[key])):
preprocess_dict_in_place(data[key][index], doubleQuoteKeys)
elif isinstance(data, list):
for index in range(len(data)):
preprocess_dict_in_place(data[index])