matiso

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

mruoss

mruoss

michalmuskala

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

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!

hubertlepicki

hubertlepicki

and there is a good reason for that: YAML is not a standardized format. In fact each and every implementation of YAML out there varies slightly. So when you generate YAML config file from most popular PHP library, it may or may not work as expected in most popular Ruby library etc.

I think @josevalim had a strong opinion on not using YAML in Elixir, and this sentiment has been picked up by the community, since the not any sort of standard argument is really good one. As a result we have a few parsers, since reading some legacy config files may be necessary - and no generators that I can see.

I’d probably generate some intermediate data format from my data (JSON?) and convert it to YAML with some external to Elixir tool (Ruby?).

matiso

matiso

You see, CSV happens to be implemented in the wildest ways, yet if customers / stakeholders of my project require a CSV export, they won’t be happy with an answer like yours.

I can understand that José does not want to use YAML FOR Elixir (e.g. he said you should not use it for Elixir configuration, and I totally agree with that). My use case is a different one. I’m building an API that needs to return a YAML file, because it is needed as a config for a separate application that I cannot change.

This, in my books, would qualify as an ugly workaround. Now I can’t say in the docs: “just curl https://foo/bar.yml > bar.yml” and you’re done! Now I’d need to deliver a script or tool to make the conversion and have the user possibly have the required runtime (or use Go, but then you have to publish a binary for every major desktop OS).

All this discussion about YAML being terrible is nice and entertaining, until you hit the real world. I’m not yet convinced of why not having a YAML generator in Elixir might be a good idea.

Where Next?

Popular in Questions Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New

Other popular topics Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

We're in Beta

About us Mission Statement