JSON is a very popular and easy-to-use data format to exchange and store. The JSON full name is JavaScript Object Notation
where data is stored which is consumable in JavaScript. With the popularity of the JSON, it is implemented in a wide range of programming languages where Python is one of them. Python provides the json
module and related methods in order to work with JSON data.
The json.dumps method is used to convert different Python data structures into the JSON string. The dictionary is very similar to the JSON where Python applications generally use the dictionary for JSON-related operations. Both dictionary and JSON use curly brackets, key-value pairs, and nested types. Also with the similarity between dictionary and a JSON string, it is very easy to read correlate them.
json.dumps() Method Syntax
As a format changer the json.dumps() method syntax is very complex according to the other methods. It provides different parameters for the conversion like ASCII enforcing, circler check separator, etc.
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
- obj is the oject which will be used as data source. Gneerally dictionary is provided as obj but also lists can be used to.
- skipkeys parameter is used to prevent raise error if items are not basic types like int, str, float, bool.
- ensure_ascii parameter is uısed to make sure all characters are ASCII compatible by escaping them.
- check_circular is used to check if some data is referenced in other parts.
- indent is used to set if the items will be intended for pretty display.
- separators parameter is used to set separator character for the specified obj.
- sort_key parameter is used to specify the key where items will be sorted.
json.dumps() Example
In this part, we will use the json.dump() method in a simple way. We will create a dictionary which contains key-value pairs and convert this dictionary into JSON format.
import json
# Creating a dictionary
d={1:'Welcome', 2:'to', 3:'PythonText'}
# Converts input dinto
# string and stores it in j
j = json.dumps(d)
print(j)
{"1": "Welcome", "2": "to", "3": "PythonText"}
json.dumps() with List
The json.dumps() method can be also used with list data structure. When we try to use the json.dumps() method with list the following output is created.
import json
# Creating a dictionary
d=[1,2,3,4,5,6]
# Converts input dinto
# string and stores it in j
j = json.dumps(l)
print(j)
[1, 2, 3, 4, 5, 6]
json.dumps() with Nested Values
The JSON data can provide nested and multiple values chained together. The json.dumps:() method can be also used for complex and nested structures like below.
import json
# Creating a dictionary
d={1:'Welcome', 2:{21:'to',22:'from'}, 3:'PythonText'}
# Converts input dinto
# string and stores it in j
j = json.dumps(d)
print(j)
{"1": "Welcome", "2": {"21": "to", "22": "from"}, "3": "PythonText"}