Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve single quote in output #741

Open
jerryhxu opened this issue Aug 10, 2023 · 2 comments
Open

Preserve single quote in output #741

jerryhxu opened this issue Aug 10, 2023 · 2 comments

Comments

@jerryhxu
Copy link

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
Copy link

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
Copy link
Member

perlpunk commented May 8, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants