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

Converting between JSON and YAML #7232

merged 2 commits into from Dec 29, 2018


None yet
4 participants
Copy link

straight-shoota commented Dec 29, 2018

This adds YAML::Any#to_json(builder) and JSON::Any#to_yaml(builder) to convert arbitrary data between both formats.

There are many uses cases for such a conversion, one example is storing arbitrary YAML input data in a database using a JSON type.

The conversion can almost entirely be implemented by delegating to raw.to_yaml(builder) and this is works quite nicely out of the box.

Since YAML is a superset of JSON, JSON::Any#to_yaml is always valid and fully reversible.

All YAML raw types except Bytes implement both #to_yaml and #to_json, so it's not a huge issue.
I've implemted Serializing YAML::Any#to_json so that it raises when raw is a Slice.
We could also consider serializing Bytes as Base64 encoded string like in YAML.
JSON serializes some data types which are distinct in YAML, such as Time as strings, thus converting from YAML to JSON is not fully reversible.

straight-shoota added some commits Dec 29, 2018


RX14 approved these changes Dec 29, 2018

@RX14 RX14 added this to the 0.27.1 milestone Dec 29, 2018

@RX14 RX14 merged commit d09d543 into crystal-lang:master Dec 29, 2018

4 of 5 checks passed

ci/circleci: test_darwin CircleCI is running your tests
ci/circleci: check_format Your tests passed on CircleCI!
ci/circleci: test_linux Your tests passed on CircleCI!
ci/circleci: test_linux32 Your tests passed on CircleCI!
continuous-integration/travis-ci/pr The Travis CI build passed

@straight-shoota straight-shoota deleted the straight-shoota:jm/feature/convert-json-yaml branch Dec 29, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment