Refactor writeJSON