Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

346
Visualizações
how to convert a text to dict in order to iterate it in python?

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

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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']
over 4 years ago · Santiago Trujillo Relatório

0

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
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda