将字节转换为字典列表

Convert bytes to a list of dictionaries

我有一个名为 xyz

的词典列表
[
  {
    "x": -11.370502,
    "y": -8.545141,
    "z": -0.083815
  },
  {
    "x": -11.36693,
    "y": -8.403456,
    "z": -0.081571
  },
  {
    "x": -11.353832,
    "y": -7.935539,
    "z": -0.074171
  },
  {
    "x": -11.315733,
    "y": -7.325937,
    "z": -0.06436599999999999
  },
  {
    "x": -11.266916,
    "y": -6.716335,
    "z": -0.054387000000000005
  },
  {
    "x": -11.185953,
    "y": -6.106733,
    "z": -0.043016
  },
  {
    "x": -11.094276,
    "y": -5.497132,
    "z": -0.030890999999999995
  },
  {
    "x": -10.982357,
    "y": -4.88753,
    "z": -0.018994999999999998
  }
]

我使用

将此写入我的sqlite3-数据库
sqlite3.Binary(pickle.dumps(border, protocol=-1))

现在我想从数据库中读回它。

xyz = bytes(sqlite3_xyz)

下一步是什么?

你只需要逆向操作即可。

test.py:

import pickle
import sqlite3

XYZ = [
    {"x": -11.370502, "y": -8.545141, "z": -0.083815},
    {"x": -11.36693, "y": -8.403456, "z": -0.081571},
    {"x": -11.353832, "y": -7.935539, "z": -0.074171},
    {"x": -11.315733, "y": -7.325937, "z": -0.06436599999999999},
    {"x": -11.266916, "y": -6.716335, "z": -0.054387000000000005},
    {"x": -11.185953, "y": -6.106733, "z": -0.043016},
    {"x": -11.094276, "y": -5.497132, "z": -0.030890999999999995},
    {"x": -10.982357, "y": -4.88753, "z": -0.018994999999999998},
]


def main():
    con = sqlite3.connect(":memory:")
    cur = con.cursor()
    cur.execute("CREATE TABLE t1 (data BLOB)")

    data = sqlite3.Binary(pickle.dumps(XYZ))

    with con:
        cur.execute("INSERT INTO t1 VALUES (?)", (data,))

    for row in cur.execute("SELECT data FROM t1"):
        data, *_ = row
        print(pickle.loads(data)[0])

    con.close()


if __name__ == "__main__":
    main()

测试:

$ python test.py
{'x': -11.370502, 'y': -8.545141, 'z': -0.083815}

Unpickling 来自未知来源的数据的安全原则仍然适用于此:

Warning

The pickle module is not secure. Only unpickle data you trust.