【问题标题】:How to convert a string to python object?如何将字符串转换为python对象?
【发布时间】:2021-04-15 10:56:01
【问题描述】:

所以,我得到了这条字符串:

"[{'id': 45, 'user_id': 2, 'cart_item_id': UUID('0fdc9e75-3d9c-4b89-912b-7058e1233432'), 'quantity': 1}]"

我想在 python 中将其转换为dictlist
谁能帮帮我

【问题讨论】:

  • 字符串不是python对象吗?
  • 在问题中它已经是字典列表了吗? @Aditya 你忘了' '吗?
  • 一种方法是将此字符串写入文件

标签: python django


【解决方案1】:

一个不错的方法是使用eval():

my_obj = eval(your_string)

一种不是很好,但更安全的方法是将其解析为json。但是必须先处理引号:

my_obj = json.loads(your_string.replace("'", '"')

选项 1 必须谨慎使用,因为eval 将评估任何 python 代码,因此容易受到攻击。 选项 2 是可以的,但可以预期带有引号的极端情况。

【讨论】:

    【解决方案2】:

    试试这个

      def Convert(string):
            li = list(string.split("-"))
            return li
          
        # Driver code    
        str1 = "[{'id': 45, 'user_id': 2, 'cart_item_id': UUID('0fdc9e75-3d9c-4b89-912b-7058e1233432'), 'quantity': 1}]"
        print(Convert(str1))
    

    【讨论】:

      【解决方案3】:

      您可以使用eval 将您的字符串评估为对象。只需确保字符串中使用/存在的类在本地或全局命名空间中可用。

      from uuid import UUID
      
      output = eval(
          """[{'id': 45, 'user_id': 2, 'cart_item_id': UUID('0fdc9e75-3d9c-4b89-912b-7058e1233432'), 'quantity': 1}]""",
      )
      

      【讨论】:

        【解决方案4】:

        这是一种方法:

        string = "[{'id': 45, 'user_id': 2, 'cart_item_id': UUID('0fdc9e75-3d9c-4b89-912b-7058e1233432'), 'quantity': 1}]"
        
        
        with open('your_file.py') as file:
            data = file.read()
        
        with open('your_file.py', 'w') as file:
            file.write(f'list_ = {string}\n{data}')
        

        这会将列表添加到文件中。

        【讨论】:

          猜你喜欢
          • 2013-10-24
          • 1970-01-01
          • 2021-08-03
          • 2021-12-07
          • 2021-02-03
          • 2011-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多