yaml / pyyaml

Canonical source repository for PyYAML
MIT License
2.54k stars 515 forks source link

Preserve single quote in output #741

Open jerryhxu opened 1 year ago

jerryhxu commented 1 year ago

I encountered an issue with preserving the single quote in output yaml file. Here is a simple example:

import yaml

random_condition = """
    - type: value
      key: some_id
      value:
        - '04549'
        - '24543'
"""

names = yaml.safe_load(random_condition)
with open('names.yml', 'w') as file:
    yaml.safe_dump(names, file)
print(open('names.yml').read())

The output yaml will display the following:

value: 
      - 04549
      - '24543'

Notice that the single quote around 04959 is not preserved. Does anyone know how to fix it? Thanks.

TheLastJediCoder commented 1 year ago

Alternative you can use custom dumper

import yaml

random_condition = """
    - type: value
      key: some_id
      value:
        - '04549'
        - '24543'
"""

class CustomDumper(yaml.Dumper):
    def represent_data(self, data):
        if isinstance(data, str) and data.isdigit():
            return self.represent_scalar('tag:yaml.org,2002:str', data, style="'")

        return super(CustomDumper, self).represent_data(data)

names = yaml.safe_load(random_condition)
with open('names.yml', 'w') as file:
    yaml.dump(names, file, Dumper=CustomDumper)
print(open('names.yml').read())
perlpunk commented 4 months ago

That's correct YAML 1.1. PyYAML implements 1.1 only so far. A leading zero means it's an octal value, so 07 or 010 are octal numbers. 08 and 09 however can't be octal numbers, so the quotes are redundant. Related issues: #486 (other issues are linked from there)

You can use the following project on top of PyYAML for YAML 1.2 support: https://pypi.org/project/yamlcore/ Since integers in YAML 1.2 can start with zeroes, all strings will be quoted:

>>> import yamlcore
>>> y = yaml.dump(names, Dumper=yamlcore.CoreDumper)
>>> print(y)
- key: some_id
  type: value
  value:
  - '04549'
  - '24543'

Also see https://perlpunk.github.io/yaml-test-schema/schemas.html