JSON is a very popular data structure used to store information in a human-readable and simple format. The long form for the JSON is the JavaScript Object Notation
. The JSON format is generally used to store and transfer data between different systems and applications. As a popular programming language Python supports JSON. The Python Dictionary data type is used to store JSON data which is very compatible from a structure point of view. The Python dictionary stores data as key-value pairs like JSON types. In order to store the provided JSON objects in Dictionary, we should use the json.dumps()
or json.dump()
methods.
Convert Python Dictionary to JSON String
We can use the json.dumps()
method to convert a dictionary into a JSON string. In the following example, we create a dictionary named person
and put some information in a key-value pair. The dumps()
method is provided via the json
module and in order to use it, we should import the json module.
import json
# Dictionary
person={
"name": "ismail",
"surname": "baydan",
"age": 38
}
# Serializing json from dictionary named person
json_object = json.dumps(person)
print(json_object)
{"name": "ismail", "surname": "baydan", "age": 38}
The JSON can be made more readable by providing the indent value. Indent is used to print the JSON in a pretty way. The indent
parameter is provided in the dumps() method.
import json
# Dictionary
person={
"name": "ismail",
"surname": "baydan",
"age": 38
}
# Serializing json from dictionary named person
json_object = json.dumps(person,indent=3)
print(json_object)
{ "name": "ismail", "surname": "baydan", "age": 38 }
Convert Python Dictionary to JSON File
The json module also provides the dumps()
method in order to put JSON data into the specified file. Before providing the file descriptor the file should be opened. After writing the JSON data the file should be closed properly. In the following example, we put the JSON data into a file named “person.json”.
import json
# Dictionary
person={
"name": "ismail",
"surname": "baydan",
"age": 38
}
# Serializing json from dictionary named person
with open("person.json", "w") as outfile:
json.dump(person, outfile)