简体   繁体   English

将 postgres bytea 写入 json

[英]Writing postgres bytea to json

Given:鉴于:

I have a column in postgres of type bytea .我在 postgres 中有一个类型为bytea的专栏。 This data was originally a string that was input by a user, and after encryption (the output being bytea ) was saved in the db.该数据原本是用户输入的string ,加密后(output为bytea )保存在db中。

Problem:问题:

I want to read the stuff column ( bytea ) and save it in json form in a file so that I can retrieve it later.我想读取 stuff 列( bytea )并将其以json形式保存在文件中,以便稍后检索。 I want the stuff data to be saved in bytea format in json as I do not have the decryption key to decrypt the data to a string.我希望将内容数据以bytea格式保存在 json 中,因为我没有将数据解密为字符串的解密密钥。

Are there better ways of doing this?有没有更好的方法来做到这一点? Is my approach too naive?我的做法是不是太天真了?

What I have tried:我试过的:

import json

import psycopg2.extras


if __name__ == '__main__':
    conn = None
    try:
        conn_string = "host='localhost' dbname='user' user='postgres'"
        conn = psycopg2.connect(conn_string)

        custom_cursor = conn.cursor('data_cursor', cursor_factory=psycopg2.extras.DictCursor)
        custom_cursor.itersize = 10000

        custom_cursor.execute("SELECT * FROM user")

        page = []
        page_number = 1

        for record in custom_cursor:
            data = {
                "user": record[record._index['user']],
                "stuff": (record[record._index['stuff']].tobytes())
            })
            page.append(data)
            if len(page) == 10000:
                file_name = "./data/page-{pn}.json".format(pn=page_number)
                with open(file_name, "w") as jfile:
                    json.dump(page, jfile)
                page.clear()
                page_number += 1
    except (Exception, psycopg2.DatabaseError) as e:
        print(e)
    finally:
        if conn is not None:
            conn.commit()
            conn.close()

Error:错误:

Object of type bytes is not JSON serializable

If you really need to store binary data in a JSON, you will have to encode it as string, for example with如果您确实需要将二进制数据存储在 JSON 中,则必须将其编码为字符串,例如使用

encode(binary_column, 'base64')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM