Open In App

Convert Escaped String to JSON in Python

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JSON (JavaScript Object Notation) is a widely used data interchange format due to its simplicity and readability. In certain scenarios, you might encounter the need to convert a JSON object into an escaped string in Python. In this article, we’ll explore some simple and commonly used methods to convert escaped strings to JSON in Python.

What is Escaped String in Python?

Escaping involves representing special characters with escape sequences, ensuring that the resulting string can be safely included in other data formats or transmitted over various channels. Similarly, other escape sequences can be used for special characters. Some common escape sequences include:

  • \n: Newline
  • \t: Tab
  • \\: Backslash
  • \': Single quote
  • \": Double quote

Convert Escaped String to JSON in Python

Below, are the Example for Convert Escaped String to JSON in Python

Example 1: Using json.loads() Method

In this example, the below code converts an escaped string containing special characters into a JSON-formatted string in Python. It uses `ast.literal_eval()` to parse the escaped string, creating an unescaped dictionary. Finally, `json.dumps()` transforms the dictionary into a valid JSON string, ready for use.

Python3




import json
import ast
 
escaped_string = '{"name": "John\\nDoe", "age": 25}'
 
# Parse the escaped string using ast.literal_eval()
unescaped_dict = ast.literal_eval(escaped_string)
 
# Convert the dictionary to JSON using json.dumps()
json_data = json.dumps(unescaped_dict)
 
print(json_data)


Output

{"name": "John\nDoe", "age": 25}


Example 2: Using ast.literal_eval() Function

In this example,below code employs a custom decoding function, `custom_decoder`, with `json.loads()` to convert an escaped string with special characters into a valid JSON format. It iterates through the dictionary’s string values, replacing escape sequences, and prints the resulting unescaped dictionary (`json_data`).

Python3




import json
 
def custom_decoder(obj):
    # Replace escape sequences in string values
    for key, value in obj.items():
        if isinstance(value, str):
            obj[key] = value.replace("\\n", "\n").replace("\\t", "\t")
    return obj
 
escaped_string = '{"name": "John\\nDoe", "age": 25}'
 
# Use json.loads() with the custom object_hook
json_data = json.loads(escaped_string, object_hook=custom_decoder)
 
print(json_data)


Output

{'name': 'John\nDoe', 'age': 25}


Conclusion

In conclusion, converting escaped strings to JSON in Python involves employing various methods, such as utilizing `json.loads()` with a custom object hook or a dedicated decoding function. These approaches effectively handle escape sequences, ensuring a seamless transition from escaped strings to valid JSON representations. Whether using standard library functions like `ast.literal_eval()` or custom decoding logic, Python provides versatile tools for working with JSON data.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads