Bootstrap FreeKB - Python (Scripting) - Convert a string to a dictionary using ast
Python (Scripting) - Convert a string to a dictionary using ast

Updated:   |  Python (Scripting) articles

Here is an example of how you can convert a string to a dictionary using ast.

#!/usr/bin/python3
import ast
var1 = '{"foo":"Hello", "bar":"World"}'
print(f"var1 {type(var1)}")

var2 = ast.literal_eval(var1)
print(f"var2 {type(var2)}")

 

Running this script should return the following because var1 is indeed a string since it's wrapped in double quotes and using ast we were able to convert the string into a dictionary.

var1 <class 'str'>
var2 <class 'dict'>

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1600ba in the box below so that we can be sure you are a human.