I do have next string:
"[
{
"name" : "name_1",
"codes" : ["some_code_1", "some_code_2"]
},
{
"name" : "name_2",
"codes" : ["some_code_1", "some_code_2"]
}
]"
How can I make this string to be just a list type ?
CodePudding user response:
You could evaluate using the builtin eval
wich i DO NOT RECOMMEND, or the "safe version" by ast wich is ast.literal_eval
, but these two each have problems. The builtin eval()
has security issues and the "safe" version is very rigorous in order to prevent malicious code.
I would suggest the JSON library
, which provides a set of tools to encode and decode with json.
Just do this:
>> 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"]
}
]
Or you could use the loads()
function instead:
>>> json.loads(to_decode)
CodePudding user response:
Try using the json
library:
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)