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:
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 Python skills with w3resource's quiz
Python: Tips of the Day
Python: Unknown Arguments Using *arguments
If your function can take in any number of arguments then add a * in front of the parameter name:
def myfunc(*arguments): for a in arguments: print a myfunc(a) myfunc(a,b) myfunc(a,b,c)
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework