improve the internal JSON encoder to more correctly detect cycles