Fix and improve JSON writing