How do I write modified content on BufWrite event?

I’m working on my first plugin to provide support for jupyter notebook files which are in a json format.

I can read those files and display them nicely. I’m now looking at how I write the content back to the file…

To do that, I need to parse the buffer and generate the necessary json - that’s working fine - but how do I tell neovim to write the json rather than the buffer content?

Do I have to replace the buffer’s content with the json, write it and then reload or is there a better way?

I am not familiar with Jupyter, but do you want to read a file with a certain filetype, generate json and write json to the same file?
If yes, then vim.api.nvim_buf_set_lines might help you. After you write the json, you can update the filetype with vim.opt.filetype = "json"