Serialize in JSON a base64 encoded data

后端 未结 3 1633
别跟我提以往
别跟我提以往 2020-12-07 13:57

I\'m writing a script to automate data generation for a demo and I need to serialize in a JSON some data. Part of this data is an image, so I encoded it in base64, but when

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 14:45

    Alternative solution would be encoding stuff on the fly with a custom encoder:

    import json
    from base64 import b64encode
    
    class Base64Encoder(json.JSONEncoder):
        # pylint: disable=method-hidden
        def default(self, o):
            if isinstance(o, bytes):
                return b64encode(o).decode()
            return json.JSONEncoder.default(self, o)
    

    Having that defined you can do:

    m = {'key': b'\x9c\x13\xff\x00'}
    json.dumps(m, cls=Base64Encoder)
    

    It will produce:

    '{"key": "nBP/AA=="}'
    

提交回复
热议问题