w3resource

Python JSON: Convert Python dictionary object to JSON data. Print the object members with indent level 4

Python JSON: Exercise-4 with Solution

Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.

Sample Solution:-

Python Code:

import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print("Original String:")
print(j_str)
print("\nJSON data:")
print(json.dumps(j_str, sort_keys=True, indent=4))

Output:

Original String:
{'4': 5, '6': 7, '1': 3, '2': 4}

JSON data:
{
    "1": 3,
    "2": 4,
    "4": 5,
    "6": 7
}
 

Flowchart:

Flowchart: Convert Python dictionary object to JSON data. Print the object members with indent level 4

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert Python objects into JSON strings. Print all the values.
Next: Write a Python program to convert JSON encoded data into Python objects.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-json-exercise-4.php