What i am trying to do is to iterate. I have this line of code in one column in a table in my database:
[{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]
i assign this to a variable order so i have:
order = [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]
then i want to iterate it. I am trying the follow:
for o in order.items():
product = o['item']
...
it doesn't work. How can i convert it?
for order in orders:
ord = order.shopping_cart_details # [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]
temp = {'order_id': order.id, 'movies': ord['item'], 'created': order.created}
full_results.append(temp)
i get string indices must be integers
Could you check the return data type after you retrieve the data from database for the following code:
[{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]
Use type(order) to determine the type of the return value. It might be that the return data for the above data is in string format. In this case, when you store the list into database, you may consider to use json.dumps() to convert the data first then later when you retrieve the data, you may use json.loads() to get back the original data type. In this case, you may consider to change the database column type to blob.
Assume the order is a string
order = '[{"item": 5, "quantity": 2},{"item": 6, "quantity": 1}]'
def doSomething():
import json
ord = json.loads(order)
values =[ v['item'] for v in ord] # if u want a single item u put values = v.pop()['item']
Or to make it more simple you can use eval function.
order = '[{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}]'
order = eval(order)
for o in order:
product = o['item']
print product