3+ Ways to Python String to Dictionary JSON[with Code Examples] - JSON Viewer

3+ Ways to Python String to Dictionary JSON[with Code Examples]

Introduction to Convert Python String to Dictionary JSON

Python String to Dictionary JSON conversion is the process of converting a string representation of a JSON object into a Python dictionary object. Converting a string to a dictionary or JSON format in python will be helpful when working with data in various formats.

String in python is basically a sequence of characters enclosed in quotation marks. Dictionary on the other hand is a collection of key value pairs enclosed in curly braces.

JSON is a simple data format used for transmitting datas in programming; it uses a straightforward text style to describe data objects as key-value pairs, arrays, and nested structures.

Let’s see some examples of how to use these methods to convert a string to a dictionary in Python.

Different Ways to Convert Python String to Dict JSON

Method 1: Using the json module with string input

The built-in json module of python can be used to convert a string to a dictionary. If the string is in JSON format then we can use this method.

Let’s see the example,

import json
# String having JSON data
employee = '{"name": "Alan", "age": 25, "designation": "Engineer"}'
# Convert string to dictionary using json.loads()
my_dict = json.loads(employee)
# Print the dictionary
print(my_dict)

In the above example, we use the function “json.loads()” to convert a JSON-formatted string to a dictionary in Python. First of all we need to import the json. There is a string called “employee” that contains the JSON data.

Key-value pairs with colons separating the keys and values make up the JSON data. The values can be strings, numbers, booleans, lists, or other objects, but the keys are strings denoted by double quotes (“”) and are always strings.

We next parse the JSON data in the employee string using the json.loads() function and turn it into a dictionary, which we save in the my_dict variable. After printing the my_dict we will get response like this,

{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}

Method 2: Using eval() function

Using eval() we can convert a string to a dictionary. The eval function evaluates the expression of the parameter passed and returns the result.

Here is one example,

# String named "employee" containing dictionary
employee = "{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}"
# Convert string "employee" to dictionary using eval()
my_dict = eval(employee)
# Print the dictionary
print(my_dict)

Here, the employee named string is created that is having a dictionary value in the form of a string.

Even if the dictionary is surrounded in single rather than double quotes, this method of encoding a dictionary in a string is still acceptable. We then evaluate the string and create a dictionary using the built-in eval() function.

When given a string argument, the eval() method attempts to run the string as a Python expression. In this instance, Python is able to evaluate the string’s dictionary literal as a dictionary.

We next use the print() function to print the completed dictionary after storing it in a variable called my_dict. The output will get like this,

{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}

Method 3: Using dict() and eval()

We can create a dictionary from a string using the built-in dict() function and eval() if the string contains a valid Python dictionary literal (curly brackets with key-value pairs separated by colons).

See the example below

# String named employee containing dictionary literal
employee = "{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}"
# Convert string to dictionary using dict()
my_dict = dict(eval(employee))
# Print the dictionary
print(my_dict)

Here the variable employee contains a dictionary in string form. The string is then evaluated using the eval() method to turn it into a dictionary literal, and the resulting literal is saved in a variable named my_eval.

The dict() function can accept a dictionary literal from the my_eval variable.

The dict() method is then used to turn my_eval into a dictionary. My_dict is a variable where the generated dictionary is kept.

The print() method is then used to print the finished dictionary.

Output:

{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}

Method 4: Using ast.literal_eval()

You can use the ast.literal_eval() function to securely evaluate an expression from a string that contains a Python literal (such a dictionary). Use it as follows:

import ast
# String named employee containing dictionary
employee = "{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}"
# Convert string to dictionary using ast.literal_eval()
my_dict = ast.literal_eval(employee)
# Print the dictionary
print(my_dict)

This example demonstrates how to convert a string containing a dictionary to a Python dictionary object using the ast.literal_eval() function.

The ast module is imported because it contains the literal_eval() function which is used to safely evaluate an expression in a string and return the corresponding Python object.

A dictionary is present in the string employee as a string literal. The employee string is then passed as a parameter to the ast.literal_eval() function. In this case, a dictionary, the matching Python object is returned when this function evaluates the expression in the string.

The variable my_dict is subsequently given the resulting dictionary. The dictionary’s contents are then printed to the console using the print() function.

The output will come like,

{'name': 'Alan', 'age': 25, 'designation': 'Engineer'}

Conclusion

In conclusion, there are several ways to change a string representation of a dictionary in Python into a dictionary object. Included in them are the use of the json module, dictionary comprehension, and the ast.literal_eval() function.

The best approach to adopt will rely on the particular programme requirements, as each method has benefits and drawbacks of its own.