How to generate nix source from json

[Original question]: How to actually coerce set to string?

Many people encountered this error but sometimes you really mean it:

  some-set = { a = 1; b = { c = "foo"; }; };
  coerceSetToString some-set

Of course, if some (sub)set contains a function, this should result in an error. I couldn’t find this magic function, maybe it exists already. It should not be hard to implement with what we have in nix language, though I don’t want to do this myself. Dealing with formatting seems boring. There are deterministic formatters like alejandra so many of the formatting issues can go away maybe…

I think it’s typically best to just use builtins.toJSON for this purpose. JSON isn’t Nix, but for data serialization it’s perfectly capable and invertible with builtins.fromJSON

Thanks for your reply!

Well, yes, but I want to generate some nix code (to create config files like plasma-manager does). The problem then becomes converting json to nix and I couldn’t find such tool either.

To rephrase the question: how can one generate nix code? It doesn’t quite matter what the source format is (since we can make it json and every sane language knows how to deal with json).

I don’t understand; what’s wrong with builtins.fromJSON?

As I understand, builtins.fromJSON returns a nix value (e.g. set or list) and I want to get a string representation of this value

then that’s builtins.toJSON

@heinwol As nix can’t know how your string should look like, you might need to create your own (recursive) string builder.