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)}")

print(f"var2 = {var2}")
print(f"var2['foo'] = {var2['foo']}")
print(f"var2['bar'] = {var2['bar']}")

 

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'>
var2 = {'foo': 'Hello', 'bar': 'World'}
var2['foo'] = Hello
var2['bar'] = World

 

Be aware that ast.literal_eval will wrap the keys and values in single quotes. But if a key or value contains one or more single quotes, then the key/value will be wrapped in double quotes. This may be problematic when you are attempting to do something with the dictionary payload.

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

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

print(f"var2 = {var2}")
print(f"var2['foo'] = {var2['foo']}")
print(f"var2['bar'] = {var2['bar']}")

 

In this example World is wrapped in double quotes because it contains a single quote.

var1 <class 'str'>
var2 <class 'dict'>
var2 = {'foo': 'Hello', 'bar': "Wor'ld"}
var2['foo'] = Hello
var2['bar'] = World



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 a0a328 in the box below so that we can be sure you are a human.