Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds
YAML::Any#to_json(builder)
andJSON::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 aSlice
.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.