nhpip
Writing a term (nested structs) in human-readable form to a text file - is there a nicer way to do this?
Hi,
I want to write a term (nested structs) in human-readable form to a text file. This is what I’ve got, there must be a better way…
i_am_a_term_now_a_string = :io_lib.format("~p.", [i_am_a_term])
|> List.flatten()
|> to_string()
File.write!("/tmp/a_term_on_your_disk", i_am_a_term_now_a_string)
Thanks
Most Liked
c4710n
If you think quoted expression is human-readable. Try to use:
quoteCode.eval_quoted
Or, just use :erlang.term_to_binary and :erlang.binary_to_term. When you want to inspect it, use something like following code instead of reading it directly.
File.read!("path/to/file")
|> :erlang.binary_to_term()
|> IO.inspect()
I think it is better to tell us your scenario. It’s an XY problem probably.
benwilson512
A bit of info will be helpful. The way to handle (most) terms in a human readable way is to use inspect to dump the data to disk, and then Code.eval_string to turn it back into a value. However this has a variety of trade offs and won’t handle arbitrary terms because things like pid values for example don’t have an output from inspect that will turn back into a pid when evaled. Whether that matters or not depends on your use case.
benwilson512
derek-zhou
I’d use ~tp.~n so there is unicode characters. and a newline between terms. also you don’t need to flatten the iostring prior to write.
Most Erlang config files are written like this and read back by consult. It is very nice and simple. Or you can use other serialization format like json, or toml but they don’t support all erlang types.







