import json dictionary = {"key1": "value1", "key2": "value2"} json_string = json.dumps(dictionary, indent=4, sort_keys=True) print(json_string)
{ "key1": "value1", "key2": "value2" }
import json list_of_dicts = [ {"name": "John", "age": 27}, {"name": "Kate", "age": 30}, {"name": "Tom", "age": 35} ] json_string = json.dumps(list_of_dicts, indent=4, sort_keys=True) print(json_string)
[ { "age": 27, "name": "John" }, { "age": 30, "name": "Kate" }, { "age": 35, "name": "Tom" } ]In both examples, we use the JSONEncoder encode method to convert the Python object into JSON format. The resulting JSON string is then printed to the console. In conclusion, the JSONEncoder encode method is available as part of the built-in json package library in Python.