简体   繁体   English

如何将字符串转换为 python object?

[英]How to convert a string to python object?

So, I have got this piece of string:所以,我得到了这条字符串:

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

And i want to convert it to list of dict in python我想将其转换为 python 中的dict list
Can anyone please help me out谁能帮帮我

A nice way would be using eval() :一个不错的方法是使用eval()

my_obj = eval(your_string)

A not very nice, but a bit safer way would be parsing it as json .一种不是很好但更安全的方法是将其解析为json But quotes have to be handled first:但必须首先处理报价:

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

Option 1 has to be used with caution as eval will evaluate any python code and thus is prone to attacks.选项 1 必须谨慎使用,因为eval将评估任何 python 代码,因此容易受到攻击。 Option 2 is ok, but a corner case with quotes is to be expected.选项 2 是可以的,但是可以预期带有引号的极端情况。

Try this尝试这个

  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))

You can use eval to evaluate your string to object.您可以使用eval将您的字符串评估为 object。 Just make sure the classes used/present in the string are available in the local or global namespace.只需确保字符串中使用/存在的类在本地或全局命名空间中可用。

from uuid import UUID

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

Here is a way to do that:这是一种方法:

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}')

this will literally add the list to the file.这实际上会将列表添加到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM