0

i have users emails stored in database like this below.

['[email protected]','[email protected]','[email protected]']

I have to get each email of all users one by one. After querying i wrote the following code.

    cur.execute("sql query")
                rows = cur.fetchall()
                for row in rows:
                    print row[2]
                    print type(row[2])
                    emails = json.loads(json.dumps(row[2]))
                    print type(emails)

<type 'str'>
<type 'unicode'>

it converts it into Unicode instead of list.

7
  • The SQL Query returns a list? What is the expected output? Commented Mar 20, 2015 at 12:46
  • the sql query returns a list of records, i also checked it by print row[2] and it prints all the list of emails as i show above. you can see in code that it says it is string. Commented Mar 20, 2015 at 12:48
  • @MTaqi: what does repr(row[2]) produce? Commented Mar 20, 2015 at 12:52
  • In any case, json.dumps() then json.loads() is not going to work, even if the row contained some kind of JSON data. Commented Mar 20, 2015 at 12:56
  • 1
    @MTaqi: using json.dumps(something) produces a JSON encoding of something, which you then decode again with json.loads(). You just encoded to JSON and that encoding was then decoded again. The only thing that achieves is that you test if a string can be JSON encoded (it can) and the result is a Unicode string with the same contents as what you started with. Commented Mar 20, 2015 at 13:04

1 Answer 1

2

Your row[2] is a string. To convert it to a list you could use ast.literal_eval:

In [29]: text = "['[email protected]','[email protected]','[email protected]']"

In [30]: import ast

In [31]: ast.literal_eval(text)
Out[31]: ['[email protected]', '[email protected]', '[email protected]']

In [32]: type(ast.literal_eval(text))
Out[32]: list
Sign up to request clarification or add additional context in comments.

4 Comments

There is no list being built. The OP is converting each email address to JSON and back.
He shows print row[2] prints ['[email protected]','[email protected]','[email protected]']. Notice there are three print statements, and three lines of output.
I am not convinced that that's the case. Also, some databases allow for JSON results in a column that is then decoded when querying. See initd.org/psycopg/docs/extras.html#json-adaptation for example.
And the print statements in the code don't match up with the output produced below the code. The list at the top of the answer is not necessarily one such row[2] being printed.

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.