Python JSON: Convert Python dictionary object to JSON data. Print the object members with indent level 4
4. Convert Python Dictionary (Sorted by Key) to JSON Data
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:

For more Practice: Solve these Related Problems:
- Write a Python program to serialize a Python dictionary into a JSON string with keys sorted and an indent level of 4 spaces.
- Write a Python program to convert a nested Python dictionary into a JSON string with sorted keys and pretty-print it with a 4-space indent.
- Write a Python program to output a Python dictionary as a JSON string with sorted keys and save the result to a file with an indent of 4 spaces.
- Write a Python program to implement a function that takes a dictionary and returns a formatted JSON string with keys sorted and indented by 4 spaces.
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.