some refactoring of #to_json methods. Thanks to Bugagazavr