matiso
Convert Elixir maps or structs to YAML
I am building an API that needs to allow the user to download a yaml config file for an external application.
I’m not sure if I’m blind, or there is no Elixir library that converts a map (or struct) into YAML? All I can find is how to decode YAML and parse it into an Elixir data structure, but not the other way around.
Most Liked
michalmuskala
Valid JSON is valid YAML. Any conforming YAML parser should be able to parse JSON. So if you don’t have any specific needs for the YAML format, doing something like:
"---\n" <> Poison.encode!(data)
will produce something any YAML parser will be able to process.
yoran
@50kudos For what it’s worth, I found myself in a similar situation. I could parse YAML with yaml-elixir but didn’t have a way to write. So I wrote a short YAML writer myself.
def to_yaml(yaml_map, indentation \\ "") do
yaml_map
|> Map.keys
|> Enum.map(
fn key ->
value = Map.fetch!(yaml_map, key)
cond do
is_bitstring(value) -> "#{indentation}#{key}: #{value}"
is_number(value) -> "#{indentation}#{key}: #{value}"
is_map(value) -> "#{indentation}#{key}:\n#{to_yaml(value, "#{indentation} ")}"
end
end
)
|> Enum.join("\n")
end
You use it as follows:
YamlElixir.read_from_file!("file.yaml")
|> Map.put(:some_key, %{some_nested_key: 123})
|> to_yaml
It’s not perfect but it suits my purposes (reading and writing the app.yaml configuration file in Google App Engine).
Thought I’d share to help others who come here while searching, like I did!
Last Post!
7rans
It actually is standardized, but implementors have taken liberties with it, and some have been reluctant to updated from 1.1 to 1.2. Yes, YAML is complex compared to JSON, but it was designed to cover more use cases. The alternative might have led to multiple ad-hoc solutions sprouting up for those additional features.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









