js-yaml icon indicating copy to clipboard operation
js-yaml copied to clipboard

adding support for number and boolean when using custom tag objects

Open chikko80 opened this issue 1 year ago • 0 comments

Improve handling of numbers and booleans in custom tags

Description

This PR enhances the YAML dumper to correctly handle numbers and booleans when using custom tags. Previously, these types were being converted to strings prematurely, leading to undesired quoting in the YAML output. The changes ensure that numbers and booleans retain their original type representation in the dumped YAML.

Changes in Output

Before this change, numbers and booleans in custom tags were being quoted in the YAML output:

number: !<foo> '3'
boolean: !<foo> 'true'

After this change, the output correctly represents numbers and booleans without quotes:

number: !<foo> 3
boolean: !<foo> true

This improvement allows for more accurate type preservation and easier parsing of the resulting YAML.

Changes

  1. Modified the writeNode function to properly handle Number and Boolean types:

    else if ((type === '[object Number]') || (type === '[object Boolean]')) {
      if (state.tag !== '?') {
        state.dump = String(state.dump);
      }
    }
    
  2. Added a new test case to verify the correct handling of numbers and booleans with custom tags:

    it('should dump multi types with custom tag and number and boolean', function () {
      // ... (test code)
    });
    

Motivation

This change is necessary to ensure that YAML output accurately represents the original data types when using custom tags. It's particularly important for configurations and data serialization where preserving the exact type of values is crucial.

Testing

A new test case has been added to verify the correct behavior. The test ensures that numbers and booleans are dumped without quotes when using custom tags.

Additional Notes

  • This change maintains backwards compatibility with existing YAML parsing behavior.
  • The modification is minimal and focused, reducing the risk of unintended side effects.

Please review and let me know if any further changes or clarifications are needed.

chikko80 avatar Sep 05 '24 01:09 chikko80