Sort results and write JSON