Json Files at Compilation Time

Hello guys, I’m wondering what is the correct way of compiling big json files. There is this json file I’ll be needing for analytics, yet I don’t want to read it and parse it every single time that is needed. Is there a way to get this json only once? perhaps at compilation time…

Hello,
yes, just use module attribute for this purpose.
Here is an example:

defmodule Test do
  @data "file.json" |> File.read!() |> Jason.decode!
  def data do
    @data
  end
end

Additionally you may want to use @external_resource flag to recompile module on file change

3 Likes

Great, I basically implemented the same module, yet I missed that module attribute. Pretty sure that will help me achieve what I had in mind. Thank you @fuelen!

tangentially related you might want to take a look at https://dashbit.co/blog/welcome-to-our-blog-how-it-was-made - where they read/parse markdown files at compile time…

2 Likes