Elegant way to encode json and write to file?

This doesn’t work.

decoded_json
|> Jason.encode!()
|> File.write!("my_file.json")

Claude recommends

# Using the pipe operator |>
data
|> Jason.encode!()
|> then(fn encoded -> File.write!("output.json", encoded) end)

# Alternative using capture syntax
data
|> Jason.encode!()
|> (&File.write!("output.json", &1)).()

This thread (Piping to `File.write/3` pipes filename, not data - #5 by cd-slash) suggests this has been discussed to death, so I’m wondering if anyone knows how to find these discussions? :slight_smile: I like history.

What is the question, how you can pipe writing to file?

The option with then should be good enough, I would avoid the option with closure as it’s extremely hard to read, otherwise you can always use your own functions:

defp write_file(content, filename) do
  File.write!(filename, content)
end

data
|> Jason.encode!()
|> write_file("test.json")

A word of advice, if you are just coming to elixir, you might have the itch to pipe everything, but please don’t do it, as it ends with unnecessary complexity.

1 Like

I hear ya. I have a healthy dose of realism. Sometimes it’s easier to read to just create an intermediate variable. Though the pipe operator is such a convenience for tacking on an extra transformation when I need it.

Back in the day you would have also the issue with hard debugging of pipes, these days this was made trivial with introduction of dbg and then, so I would guess the only rule of the thumb is to have them readable.

1 Like

Am I breaking any laws thumbs by using |> Kernel.<>("\n<!-- End of page #{page_number} -->\n") at the end of a pipe to append some text?

I think you are breaking hearts of people that expected you to write code they would understand :smile: .

I would personally never approve a MR having such a line for application code, this is the same as someone using Integer.addExact(5, 10) in java, I need to go and open the documentation to understand wtf is going on.

I would. It’s fine, you’re technically only adding a pipe and the Kernel word compared to the other code.

There are more egregious examples of what I wouldn’t approve though, like that closure above that’s also called immediately after being defined. That’s just code golf…