0

Trying to insert following JSON String as is without formatting

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"
            }
        }
    }
}

in to following PostgreSQL DB

CREATE TABLE records
(
  id text,
  record json
) 

Code I am using to perform the insert operation

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

Error I am getting

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

Is this the right syntax to store json string as part of the column

3
  • 2
    You should remove your json.loads call. So it will be json.dumps(str). Commented Nov 12, 2018 at 21:19
  • Thanks that solved it Commented Nov 12, 2018 at 22:52
  • @sashaaero put it as your answer.. So this question will not show in unanswered.. Commented Nov 13, 2018 at 0:03

1 Answer 1

2

json.loads(obj) creates json object from string data.

json.dumps(obj) creates string from json object.

So you should change json.dumps(json.loads(str)) to json.dumps(str).

P.S.: I'd also don't recommend to call your variables as type names like str, int. You are making str() and int() call unable from current scope.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.