How to serialize a transaction to JSON with Python SDK?

Hello,
I try to get the json for a transaction but I failed with :
json.dumps(tx.dictify(), indent=4)
It gives error : TypeError: Object of type bytes is not JSON serializable because some fields are not JSON serializable (like the group id which has type bytes).

Do you now if the Python SDK already offers a simple way to get the JSON representation of a transaction ?

In the meantime, I wrote this function to serialize a transaction (signed or not) to an indented JSON string :

def serialize_tx_to_json(tx):
    def bytes_to_base64_str(bytes_):
        return base64.b64encode(bytes_).decode()

    def change_bytes_to_string_recursive(dict_):
        assert hasattr(dict_, "items")
        new_dict = dict()
        for key, value in dict_.items():
            if type(value) is bytes:
                new_value = bytes_to_base64_str(value)
            elif hasattr(value, "items"):
                new_value = change_bytes_to_string_recursive(value)
            else:
                new_value = value
            new_dict[key] = new_value
        return new_dict
    
    return json.dumps(change_bytes_to_string_recursive(tx.dictify()), indent=4)
1 Like

Hi, just use message pack encode functions inside algosdk.

txn_e = msgpack_encode(txn)
return {'txn': txn_e }

Hope it helps

Thanks but I needed a readable JSON. For now I use my code above which is working fine (for classic transactions at least).