Convert Elixir maps or structs to YAML

@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!

6 Likes