0

I have created a table in PostgreSQL with a JSON column and when I try to Insert data into the column It returns an error. I try to get those data from an api using python: here is the what I have done so far:

defaulturl = 'https://pokeapi.co/api/v2/pokemon/1/'
sql = 'CREATE TABLE IF NOT EXISTS pokeapi (id INTEGER, body JSONB);'
print(sql)
cur.execute(sql)

sql = 'SELECT COUNT(body) FROM pokeapi;'
count = myutils.queryValue(cur, sql)
if count < 1:
    objects = ['films', 'species', 'people']
    for obj in objects:
        sql = f"INSERT INTO pokeapi (body) VALUES ( 'https://pokeapi.co/api/v2/{obj}/1/' )";
        print(sql)
        cur.execute(sql, (defaulturl))
    conn.commit()

I try to loop through and retrieve the JSON data for urls ending in 1 to 100 and store it in the table in the body column. Note that the url is in the API and API have the following structure:

{
ability: {
name: "overgrow",
url: "https://pokeapi.co/api/v2/ability/65/"
},
is_hidden: false,
slot: 1
}

Error Image

1 Answer 1

2

You're trying to put the URL into the body column. This has 2 issues:

  • You didn't really mean to put it there
  • The URL doesn't validate as JSON so the database complains about the URL not being a valid JSON string.

Fix it by replacing (body) with (url, body), in the INSERT.

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

3 Comments

hello, @pletnes and thank you for the answer I really appreciate it. Now I change it with (url), in the INSERT it sent back it without error
Hi @fyardlest, if you have found pletnes answer useful and it solves your problem, consider choosing his answer as the selected one for this question :)
Thank you @Arson0

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.