Moved JSON writing code to separate method