data ='{"nodes":[{"id":-1,"name":"default","type":"root","type_id":11,"children":[-2,-3,-4]}]}'# data类型是str,想要变为dict类型,去掉最外面的单引号
data_dict ={'nodes':[{'id':-1,'name':'default','type':'root','type_id':11,'children':[-2,-3,-4]}]}
1、通过json转换
import json
data ='{"nodes":[{"id":-1,"name":"default","type":"root","type_id":11,"children":[-2,-3,-4]}]}'
data_dict = json.loads(data)print(data_dict){'nodes':[{'id':-1,'name':'default','type':'root','type_id':11,'children':[-2,-3,-4]}]}# json虽然能解决我这个问题,但是用json有限制条件
json规定 数组或对象之中的字符串必须是用双引号,不能用单引号
test ="{'test': 'test_code'}"
test_dict = json.loads(test)print(test_dict)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)# 所以json这种方法不可取
2、通过eval转换
data ='{"nodes":[{"id":-1,"name":"default","type":"root","type_id":11,"children":[-2,-3,-4]}]}'print(eval(data))
test ="{'test': 'test_code'}"print(eval(test))# eval方法虽然没有转换问题,但存在安全性问题,因为eval不仅能解析数据类型还能解析一些恶意输入命令,可能造成不好的影响
3、通过literal_eval转换
import ast
data ='{"nodes":[{"id":-1,"name":"default","type":"root","type_id":11,"children":[-2,-3,-4]}]}'print(ast.literal_eval(data))
test ="{'test': 'test_code'}"print(ast.literal_eval(test))# literal_eval只会执行合法的python类型,如果有问题会自动跑出去异常