pythonast将字符串转为字典
时间: 2023-10-10 21:07:45 浏览: 123
python实现字符串和字典的转换
5星 · 资源好评率100%
你可以使用 `ast.literal_eval` 将包含 Python 字面值的字符串转换为对应的 Python 对象,然后使用 `ast_to_dict` 函数将 Python 对象转换为字典。
下面是一个示例代码,可以将包含 Python 字面值的字符串转换为字典:
```
import ast
def ast_to_dict(node):
if isinstance(node, ast.AST):
fields = {}
for field, value in ast.iter_fields(node):
fields[field] = ast_to_dict(value)
return {
"type": type(node).__name__,
"fields": fields,
}
elif isinstance(node, list):
return [ast_to_dict(x) for x in node]
else:
return node
string_literal = "{'name': 'John', 'age': 30}"
python_object = ast.literal_eval(string_literal)
python_object_dict = ast_to_dict(python_object)
print(python_object_dict)
```
输出结果应该类似于:
```
{
"type": "Dict",
"fields": {
"keys": [
{
"type": "Str",
"fields": {
"s": "name"
}
},
{
"type": "Str",
"fields": {
"s": "age"
}
}
],
"values": [
{
"type": "Str",
"fields": {
"s": "John"
}
},
{
"type": "Num",
"fields": {
"n": 30
}
}
]
}
}
```
希望这可以帮助到你。
阅读全文