Python嵌套对象不可序列化

时间:2018-01-28 20:39:04

标签: python json

Transaction.py

from TransactionInput import TransactionInput
import unittest
from io import BytesIO
from binascii import unhexlify
import json


class Transaction:
    def __init__(self, version, inputs):
        self.version = version
        self.inputs = inputs

    @classmethod
    def parse(cls, stream):
        version = int.from_bytes(stream.read(4), byteorder='little')

        inputs_size = int.from_bytes(stream.read(1), byteorder='big')
        tx_inputs = []
        for i in range(0, inputs_size):
            tx_input = TransactionInput.parse(stream)
            tx_inputs.append(tx_input)

        return cls(version, tx_inputs)


class TestTransaction(unittest.TestCase):
    def test_parse(self):
        raw_transaction = '0100000001280594d0869749bd0f0e76074637a41a534cf96b0f7787aafe36f2c466ae3c50000000006b48304502204b39b9d63d0718052bd64c120f768a5eb083a8184a31409520104bc2a508af4f022100f62d5ce8b74a61e0075b8f3dc14df8b2e4714a962a0644e458d56bd1cb92915e012103ca545c610051cb0cca1539d95b58dd87075f97e154e9c652bafe4379424c1ba9ffffffff02672df26d010000001976a91485c359dfc971723d6724d42c60b362cce7fe01d488ac4029a1d1000000001976a9147c228e5f129213301b84b3a28aa22bf3556568e588ac00000000';
        bytes = unhexlify(raw_transaction)
        transaction = Transaction.parse(BytesIO(bytes))
        print(json.dumps(vars(transaction), sort_keys=True, indent=4))


if __name__ == '__main__':
    unittest.main()

TransactionInput.py

from ScriptSig import ScriptSig
from binascii import hexlify


class TransactionInput:
    def __init__(self, prev_tx_hash):
        self.prev_tx_hash = prev_tx_hash

    @classmethod
    def parse(cls, stream):
        prev_tx_hash = hexlify(stream.read(32)).decode('ascii')
        return cls(prev_tx_hash)

错误

TypeError: Object of type 'TransactionInput' is not JSON serializable

我有Transaction对象,它有嵌套的TransactionInput对象。我试图将此事务对象转换为JSON。当我这样做而没有内心对象时,它起作用了。但是在添加内部对象时,它引发了一个错误。有人能帮我吗?我愿意为JSON coversion提供更好的解决方案/库

1 个答案:

答案 0 :(得分:1)

问题是你的transaction对象包含TransactionInput类型的成员(不可序列化 - 只有基本类型,列表和词典):

{'version': 1, 'inputs': [<TransactionInput.TransactionInput object at 0x1082cd0f0>]}

有几种方法可以解决这个问题,但由于您使用的是相对简单的对象,我建议您自己处理序列化:

class TransactionInput:
    def __init__(self, prev_tx_hash):
        self.prev_tx_hash = prev_tx_hash

    def to_json(self):
        """ This serializes each TransactionInput"""
        return "{{prev_tx_hash: {}}}".format(self.prev_tx_hash) 

 class Transaction:
    def __init__(self, version, inputs):
        self.version = version
        self.inputs = inputs


    def to_json(self):
        """ This serializes the whole Transaction object"""
        inputs_json = ','.join(_input.to_json() for _input in self.inputs)

        return '{{version: {}, inputs: [{}]}}'.format(self.version, self.inputs)

有了这个,您只需序列化Transaction来电transaction.to_json()即可,您的考试将通过。