Is there a way to read a yaml file and get back a set?

This comes up a lot. For example, consider alacritty’s colorscheme configuration.
It has a colors entry that matches the yaml config 1:1.
It would be nice if we can have config.colors = fromYaml ./colors.yaml inside alacritty.nix.
Currently I have to copy the yaml file, then manually change it to nix syntax when I want to experiment with stuff like this.

1 Like

Probably the best you can do is turn your YAML file into a JSON with:

$ echo -e 'a:\n  b: 1\n  c: 2' | nix run nixpkgs#yj

And then use builtins.readFile and builtins.fromJSON

You could also use a derivation that does the yj step automatically (only if import-from-derivation is ok to your use case)


(I just use this in my config)

1 Like

These days i tend to customize applications this way: nixfiles/default.nix at 2b2abcd07ede0df56360a8cda50a919a65864f8c · gytis-ivaskevicius/nixfiles · GitHub (For more examples refer to /overlays/g-*)

I just find it easier due to less clutter in module files. Also, you can nix run it :slight_smile:

1 Like

Nix can only natively “import” TOML, JSON and Nix. As Nix lacks YAML support for this, you have three options:

  1. Use JSON. Since YAML is a superset of JSON, you could limit yourself to using JSON in this use case. Other applications should still be able to interpret the YAML file correctly as well.
  2. Use import-from-derivation to import the YAML file by converting it to JSON first. We could use yj for this as proposed above: let importYaml = file: builtins.fromJSON (builtins.readFile (pkgs.runCommandNoCC "converted-yaml.json" ''${pkgs.yj}/bin/yj < "${file}" > "$out"'')); in importYaml ./colors.yaml. This has some drawbacks, mainly that yj needs to be available at evaluation time (so if it’s not cached you are looking at building it) and evaluation will block on the build of the converted JSON (and yj…) as evaluation is single-threaded.
  3. Write a YAML implementation in pure Nix. This is probably an extreme measure; Despite theoretically useful, certainly a lot of nontrivial work.

Looking at GitHub search for fromYaml, IFD is the most common approach. I only noticed a single repo attempting to parse (a subset of) YAML using Nix.