Converting JSON to String in Python using the json module

AuthorSumit Dey Sarkar

Pubish Date30 Apr 2023

categoryPython

In this tutorial we will learn Converting JSON to String in Python using the json module.

 

Converting JSON to String in Python using the json module

 

Converting JSON to String in Python using the json module

The json module in Python is used to convert a JSON object or a JSON string to a string.

 

Let's see an example -

import json

# Example JSON object
json_obj = {
    "name": "John Doe",
    "age": 30,
    "isMarried": True,
    "hobbies": ["reading", "traveling", "music"]
}

# Convert JSON object to a string
json_str = json.dumps(json_obj)

# Print the result
print(json_str)

In the above example, we first imported the json module. Then we created a JSON object json_obj that contains some data. Finally, we allocated the output of the JSON object's conversion to a string using the json.dumps() method to the json_str variable. We then printed the result using the print() function.

 

If you have a JSON string, you can use the json.loads() function to convert it into a JSON object, which can then be convert into a string using the json.dumps() method.

 

Here's an example:

import json

# Example JSON string
json_str = '{"name": "John Doe", "age": 30, "isMarried": true, "hobbies": ["reading", "traveling", "music"]}'

# Convert JSON string to a JSON object
json_obj = json.loads(json_str)

# Convert JSON object to a string
json_str = json.dumps(json_obj)

# Print the result
print(json_str)

In this example, we first defined a JSON string json_str. The JSON text was then transformed into a JSON object (json_obj) using the json.loads() method. Finally, we allocated the output of the JSON object's conversion to a string using the json.dumps() method to the json_str variable. We then printed the result using the print() function.

 

Comments 0

Leave a comment