Convert between toml, yaml and json in shortcode

I have some code examples in toml that are displayed in code blocks. I’ve seen in the Hugo docs that these examples are provided in all three forms, toml, yaml and json. Is there a way to convert between these formats inside of a shortcode programmatically to avoid the duplication of my examples? It would also need be nice to convert the comments inside of the toml files.

You can 1) transform.Unmarshal and then 2) transform.Remarshal it in other format.

{{ $code := printf "%s\n%s" "foo: bar # my comment" "hello: world" }}
{{ $lang := "toml" }}
{{ $toml := $code | transform.Unmarshal | transform.Remarshal $lang }}
{{ $toml | warnf "\n%s" }}

But I don’t think it’s able to keep the comments.

Comments are not valid in JSON format.


Looks pretty magic as the transform.Unmarshal does not take a lang specifier. Will try this out later.

Well comments would be really nice to have, but you’re right, comments are not allowed in plain JSON. I modifiied my request above.

Found the related issue on GitHub.

1 Like