The Wayback Machine - https://web.archive.org/web/20240913191608/https://www.geeksforgeeks.org/json-dumps-in-python/
Open In App

json.dumps() in Python

Last Updated : 19 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JSON is an acronym that stands for JavaScript Object Notation. Despite its name, JSON is a language agnostic format that is most commonly used to transmit data between systems, and on occasion, store data. Programs written in Python, as well as many other programming languages, can ingest JSON formatted data, and can serialize data in memory into the JSON format. Python supports JSON through a built-in package called json. To use this feature, import the json package into the Python script or module in which you wish to serialize or deserialize your data. JSON utilizes comma delimited key value pairs contained in double quotes and separated by colons. The body of a JSON file can be delimited in curly braces { } or square braces [] (also known as “brackets” in some locales). The JSON format appears to be similar to the dictionary in Python, but the specifics of the JSON format have significant differences, so use care when working with both formats.

Note: For more information, refer to Read, Write and Parse JSON using Python

Json.dumps()


json.dumps() function will convert a subset of Python objects into a json string. Not all objects are convertible and you may need to create a dictionary of data you wish to expose before serializing to JSON.
 

Syntax: 
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)
Parameters: 
obj: Serialize obj as a JSON formatted stream 
skipkeys: If skipkeys is True (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError. 
ensure_ascii: If ensure_ascii is True (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is False, these characters will be output as-is. 
check_circular: If check_circular is False (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
allow_nan: If allow_nan is False (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is True, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used. 
indent: If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as “\t”), that string is used to indent each level. 
separators: If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘, ‘, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘, ‘, ‘:’) to eliminate whitespace. 
default: If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised. 
sort_keys: If sort_keys is True (default: False), then the output of dictionaries will be sorted by key.


Example #1: Passing the Python dictionary to json.dumps() function will return a string. 
 

Python3
import json

# Creating a dictionary
Dictionary ={1:'Welcome', 2:'to',
            3:'Geeks', 4:'for',
            5:'Geeks'}
 
# Converts input dictionary into
# string and stores it in json_string
json_string = json.dumps(Dictionary)
print('Equivalent json string of input dictionary:',
      json_string)
print("        ")

# Checking type of object
# returned by json.dumps
print(type(json_string))

Output
 

Equivalent json string of dictionary: {“1”: “Welcome”, “2”: “to”, “3”: “Geeks”, “4”: “for”, “5”: “Geeks”} 
<class ‘str’>


Example #2: By setting the skipkeys to True(default: False) we automatically skip the keys that are not of basic type.
 

Python3
import json


Dictionary ={(1, 2, 3):'Welcome', 2:'to',
            3:'Geeks', 4:'for',
            5:'Geeks'}


# Our dictionary contains tuple
# as key, so it is automatically 
# skipped If we have not set
# skipkeys = True then the code 
# throws the error 
json_string = json.dumps(Dictionary, 
                         skipkeys = True)

print('Equivalent json string of dictionary:', 
      json_string)

Output 
 

Equivalent json string of dictionary: {“2”: “to”, “3”: “Geeks”, “4”: “for”, “5”: “Geeks”} 
 


Example #3: 
 

Python3
import json


# We are adding nan values
# (out of range float values)
# in dictionary
Dictionary ={(1, 2, 3):'Welcome', 2:'to',
            3:'Geeks', 4:'for',
            5:'Geeks', 6:float('nan')}

# If we hadn't set allow_nan to 
# true we would have got 
# ValueError: Out of range float 
# values are not JSON compliant
json_string = json.dumps(Dictionary,
                         skipkeys = True,
                         allow_nan = True)

print('Equivalent json string of dictionary:', 
      json_string)

Output : 
 

Equivalent json string of dictionary: {“2”: “to”, “3”: “Geeks”, “4”: “for”, “5”: “Geeks”, “6”: NaN} 


Example #4: 
 

Python3
import json


Dictionary ={(1, 2, 3):'Welcome', 2:'to',
            3:'Geeks', 4:'for',
            5:'Geeks', 6:float('nan')}

# Indentation can be used 
# for pretty-printing
json_string = json.dumps(Dictionary, 
                         skipkeys = True, 
                         allow_nan = True,
                         indent = 6)

print('Equivalent json string of dictionary:', 
      json_string)

Output: 
 

Equivalent json string of dictionary: {
"2": "to",
"3": "Geeks",
"4": "for",
"5": "Geeks",
"6": NaN
}


Example #5: 
 

Python3
import json

Dictionary ={(1, 2, 3):'Welcome', 2:'to',
            3:'Geeks', 4:'for',
            5:'Geeks', 6:float('nan')}

# If specified, separators should be
# an (item_separator, key_separator)tuple
# Items are separated by '.' and key,
# values are separated by '='
json_string = json.dumps(Dictionary,
                         skipkeys = True, 
                         allow_nan = True,
                         indent = 6,
                         separators =(". ", " = "))

print('Equivalent json string of dictionary:',
      json_string)

Output: 
 

Equivalent json string of dictionary: {
"2" = "to".
"3" = "Geeks".
"4" = "for".
"5" = "Geeks".
"6" = NaN
}


Example #6: 
 

Python3
import json

Dictionary ={'c':'Welcome', 'b':'to',
            'a':'Geeks'}

json_string = json.dumps(Dictionary,
                         indent = 6,
                         separators =(". ", " = "),
                         sort_keys = True)

print('Equivalent json string of dictionary:',
      json_string)

Output: 
 

Equivalent json string of dictionary: {
"a" = "Geeks".
"b" = "to".
"c" = "Welcome"
}


 json.dumps() in Python – FAQs

What do json.dumps() do in Python?

‘json.dumps()’ is a method in the json module that converts a Python object (like a dictionary) into a JSON formatted string.

import json

data = {'name': 'John', 'age': 30}
json_string = json.dumps(data)

print(json_string) # Output: '{"name": "John", "age": 30}'

How is json.dump() used?

‘json.dump()’ is used to serialize a Python object (like a dictionary) and write it to a file as a JSON formatted string.

import json

data = {'name': 'John', 'age': 30}

with open('data.json', 'w') as f:
json.dump(data, f)

What is the difference between JSON dump() and JSON dumps()?

  • json.dumps() converts a Python object to a JSON formatted string.
  • json.dump() serializes a Python object and writes it to a file as a JSON formatted string.

How to write JSON dump() to a file?

Use ‘json.dump()’ to write JSON data to a file, providing the data and an open file object in write mode (‘w’).

import json

data = {'name': 'John', 'age': 30}

with open('data.json', 'w') as f:
json.dump(data, f)

What is the purpose of the dump() and load() methods in Python?

  • dump() serializes a Python object into a JSON formatted string and writes it to a file.
  • load() deserializes a JSON formatted string from a file and converts it into a Python object.


Similar Reads

Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Use jsonify() instead of json.dumps() in Flask
Here, we will understand the jsonify() function in the Flask web framework for Python that converts the output of a function to a JSON response object. It is similar to the json.dumps() function in the Python standard library, which converts a Python object to a JSON-formatted string. What is jsonify() The jsonify() function is useful in Flask apps
4 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
JSON Formatting in Python
JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Py
3 min read
Working With JSON Data in Python
JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which cont
6 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}
4 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard module
3 min read
Pretty Print JSON in Python
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Read, Write and Parse JSON using Python Pretty Print JSON Whenever d
2 min read
Python - JSON to XML
A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSON
5 min read
Python - XML to JSON
A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server. A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSO
4 min read
How to import JSON File in MongoDB using Python?
Prerequisites: MongoDB and Python, Working With JSON Data in Python MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. JSON stands for JavaScript Object Notation. It is an open standard file format, and data int
2 min read
Encoding and Decoding Custom Objects in Python-JSON
JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For
5 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the det
2 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
Deserialize JSON to Object in Python
Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module to perform this task : loads() : to deserialize a
2 min read
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
Python JSON
Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects including parsing, serializing, deserializing, and
3 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
How to return a json object from a Python function?
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json and this module can be used to convert a python dictionary to JSON object. In Python dictionary is used to
2 min read
How to compare JSON objects regardless of order in Python?
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primaril
2 min read
How to read a JSON response from a link in Python?
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which he
2 min read
Convert HTML source code to JSON Object using Python
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
3 min read
Extract JSON from HTML using BeautifulSoup in Python
In this article, we are going to extract JSON from HTML using BeautifulSoup in Python. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.pip install bs4requests: Request allows you to send HTTP/1
3 min read
How to communicate JSON data between Python and Node.js ?
The following article covers how to communicate JSON data between Python and Node.js. Suppose we are working with the Node.js application, and we want to make use of a specific library that is only available in python or vice versa. We should be able to share the results from one language to another and to achieve it, we will use the JSON as it is
7 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
JSON Parsing Errors in Python
JSON is a widely used format for exchanging data between systems and applications. Python provides built-in support for working with JSON data through its JSON module. However, JSON parsing errors can occur due to various reasons such as incorrect formatting, missing data, or data type mismatches. There are different JSON parsing errors that can oc
6 min read
Article Tags :
Practice Tags :