我有下一个字符串:
"[
{
"name" : "name_1",
"codes" : ["some_code_1", "some_code_2"]
},
{
"name" : "name_2",
"codes" : ["some_code_1", "some_code_2"]
}
]"
如何使这个字符串只是一个列表类型?
您可以使用内置的eval
(不推荐)或"安全版本"进行评估。最后一个是ast.literal_eval
,但是这两个都有问题。内置eval()
存在安全问题,"安全";版本非常严格,以防止恶意代码。
我建议使用JSON library
,它提供了一组使用json进行编码和解码的工具。
就这样做:
>> import json
>> to_decode = """
[
{
"name" : "name_1",
"codes" : ["some_code_1", "some_code_2"]
},
{
"name" : "name_2",
"codes" : ["some_code_1", "some_code_2"]
}
]"""
>>> #to decode it here is the solution...
>>> json.JSONDecoder().decode(to_decode)
[
{
"name" : "name_1",
"codes" : ["some_code_1", "some_code_2"]
},
{
"name" : "name_2",
"codes" : ["some_code_1", "some_code_2"]
}
]
或者您可以使用loads()
函数代替:
>>> json.loads(to_decode)
尝试使用json
库:
import json
sampleString = """
[
{
"name" : "name_1",
"codes" : ["some_code_1", "some_code_2"]
},
{
"name" : "name_2",
"codes" : ["some_code_1", "some_code_2"]
}
]
"""
processedList = json.loads(sampleString)
print(processedList)