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

Inconsistent/Wrong Type casting when using yaml.dump/safe_dump #794

Closed
stuartornum opened this issue May 8, 2024 · 2 comments
Closed

Inconsistent/Wrong Type casting when using yaml.dump/safe_dump #794

stuartornum opened this issue May 8, 2024 · 2 comments

Comments

@stuartornum
Copy link

stuartornum commented May 8, 2024

Hi,

Think I've found an issue when using yaml.dump and safe_dump. (Using pyyaml v6.0.1)

import yaml

data = {
    "buildings": [
        {
            "building_id": "0000007",
            "building_name": "100 central square"
        },{
            "building_id": "0000008",
            "building_name": "Headquarters"
        },{
            "building_id": "0000009",
            "building_name": "Test"
        },{
            "building_id": "0000010",
            "building_name": "London House"
        },
    ]
}

print(yaml.dump(data))

The output

Notice 0000008 and 0000009 are not strings, like the others.

buildings:
- building_id: '0000007'
  building_name: 100 central square
- building_id: 0000008
  building_name: Headquarters
- building_id: 0000009
  building_name: Test
- building_id: '0000010'
  building_name: London House
@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
>>> print(yaml.dump(data, Dumper=yamlcore.CoreDumper))
buildings:
- building_id: '0000007'
  building_name: 100 central square
- building_id: '0000008'
  building_name: Headquarters
- building_id: '0000009'
  building_name: Test
- building_id: '0000010'
  building_name: London House

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

@stuartornum
Copy link
Author

Using yamlcore worked a treat! Thank you!

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

2 participants