代码之家  ›  专栏  ›  技术社区  ›  K.Pil

在PostgreSQL表列中插入JSON字符串

  •  0
  • K.Pil  · 技术社区  · 8 年前

    正在尝试按原样插入以下JSON字符串而不设置格式

    str={
        "Trial": {
            "@id": "xxxxx",
            "key1": "aaaaaaaa (BAL-8557) aaaaaaaaaaaaaaaaaa",
            "key2": "aaaaaaaaaaaaa , aaaaaaaaaaaaaaaaaaa",
            "key3": "Yes",
            "key4": "No",
            "key5": {
            "key5": [{
                        "@type": "ABC",
                        "$": "ABC121 "
                    },
                    {
                        "@type": "ABC",
                        "$": "ABC12133 "
                    }]
            },
            "Indications": {
                "Indication": {
                    "@id": "1308",
                    "$": "aaaaaa"
                }
            }
        }
    }
    

    在下面的PostgreSQL数据库中

    CREATE TABLE records
    (
      id text,
      record json
    ) 
    

    我用来执行插入操作的代码

    cur = conn.cursor()
    cur.execute("INSERT INTO trial_records(id, record) VALUES (%s, %s)", ('1', json.dumps(json.loads(str))))
    

    我犯了一个错误

    the JSON object must be str, bytes or bytearray, not 'dict' 
    

    这是将json字符串存储为列的一部分的正确语法吗

    1 回复  |  直到 8 年前
        1
  •  2
  •   sashaaero    8 年前

    json.loads(obj) 从字符串数据创建json对象。

    json.dumps(obj) 从json对象创建字符串。

    json.dumps(json.loads(str)) 到 json.dumps(str) .

    str , int str() 和 int()