Skip to content

Add :stringify_names option to convert symbol keys to string for dumping - #621

Merged
tenderlove merged 1 commit into
ruby:masterfrom
fnordfish:dump-stringify-names
Jan 18, 2024
Merged

tenderlove merged 1 commit into
ruby:masterfrom
fnordfish:dump-stringify-names

Conversation

@fnordfish

Copy link
Copy Markdown
Contributor

When dumping larger and/or nested Hashes, it would be useful to let Psych treat symbol keys as string keys to avoid building a new hash with string keys, just for the sake of dumping.

:stringify_names for dumping is conceptually the reverse of :symbolize_names for loading:

yaml = "---\nfoo: bar\n"
Psych.dump(Psych.load(yaml, symbolize_names: true), stringify_names: true) == yaml # => true

@fnordfish

Copy link
Copy Markdown
Contributor Author

Did a small benchmark, comparing symbolize_names: true vs. manual deep stringify keys: https://gist.github.com/fnordfish/4b22aed6281800897e56399d6c53c0be

While overall performance gains seem to be within margin of error, memory usage is consistently down.

@tenderlove tenderlove left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like a fine feature, but is the option name the right thing? It's stringify_names, but that seems pretty ambiguous from the reader's perspective. Maybe stringify_symbol_keys or something?

@fnordfish

Copy link
Copy Markdown
Contributor Author

I'm absolutely not married to the name.

But just for the sake of the argument, symbolize_names does also only work on string keys:

Psych.safe_load("---\n!ruby/object:DateTime 2024-01-17 11:19:12.359689000 +01:00: value\nkey: value\n", symbolize_names: true, permitted_classes: [Time, DateTime])
# => {#<DateTime: 2024-01-17T11:19:12+01:00 ((2460327j,37152s,359689000n),+3600s,2299161j)>=>"value", :key=>"value"}

@tenderlove

Copy link
Copy Markdown
Member

But just for the sake of the argument, symbolize_names does also only work on string keys:

Ya, you're right. Looking through commit history, it seems like that came from JSON.parse. I guess since we have documentation it's probably fine. I'll merge this. Thank you!

@tenderlove
tenderlove merged commit be0ba74 into ruby:master Jan 18, 2024
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

Successfully merging this pull request may close these issues.

2 participants