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
jQuery | Dimensions
The JQuery Dimensions is an inbuilt method in jQuery which is used to work with the dimensions of various elements and browser window. There are several dimension methods in JQuery Dimension.jQuery Dimension Methods: width(): This method sets or returns the width of the element excluded padding, bor
3 min read
What Is VH in CSS?
When designing responsive websites, it's important to create layouts that adapt to different screen sizes and orientations. CSS offers several units to help with this, and one of the most powerful for responsive design is the vh unit. In this article, we’ll explore what vh is in CSS, how it works, a
4 min read
CSS Only Masonry Layouts
A Masonry layout is one in which things are placed one after the other in a straight line. Objects will migrate up into any gaps left by shorter items in the first line as they move onto the next line. It's comparable to a grid layout with auto-placement, except the rows don't follow a tight grid. M
3 min read
How to make images responsive ?
In today's world, mobile internet usage is growing at a fast pace, so it has become necessary for websites to have responsive designs for devices of different sizes. Websites that can change their appearance dynamically according to the device or the screen in which it is viewed are called responsiv
3 min read
HTML | DOM Style padding Property
The Style padding property is used for setting or returning the padding of an element. The Style padding property can be used in 4 different ways : div {padding: 30px} -In this case, all the four sides have a padding of 30px.div {padding: 100px 50px} -In this case, the top and bottom padding will be
4 min read
How to detect the change in DIV's dimension ?
The change in a div's dimension can be detected using 2 approaches: Method 1: Checking for changes using the ResizeObserver Interface The ResizeObserver Interface is used to report changes in dimensions of an element. The element to be tracked is first selected using jQuery. A ResizeObserver object
4 min read
Explain the working of calc() function in CSS
The calc() function in CSS allows for dynamic calculations within property values, combining different units and mathematical operations. It enhances flexibility and responsiveness in layouts by enabling precise control over dimensions and spacing. Working of calc() functionThe calc() function in CS
3 min read
Primer CSS Responsive Grids
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by
3 min read
How to design a responsive Web Page in HTML ?
In this article, we will learn how to design a responsive Web Page in HTML. Responsive web design (RWD) is a web development approach that creates dynamic changes to the appearance of a website, depending on the screen size and orientation of the device being used to view it. RWD can be obtained by
3 min read
How to Set Viewport Height & Width in CSS ?
Set viewport height and width in CSS is essential for creating responsive and visually appealing web designs. We'll explore the concepts of setting viewport height and width by using various methods like CSS Units, Viewport-Relative Units, and keyframe Media Queries. Table of Content Setting viewpor
3 min read
Tachyons Layout Heights
Tachyons is a free and open-source toolkit that is used to create a responsive. In this article, we will see how to increase the height of the HTML element using the Tachyons. Tachyons Layout Heights is used to set the height of the element by adding a specific class of specific scale. It contains t
2 min read
How to Define Two Column Layout using Flexbox?
A two-column layout is a common design pattern where content is arranged into two columns, making efficient use of space and enhancing readability. Using CSS Flexbox, this layout becomes flexible and responsive, automatically adjusting to different screen sizes and orientations. In this article, we
3 min read
How To Create a Responsive Table in CSS ?
A responsive table in CSS automatically changes to fit any screen size. It stays easy to read on small screens, like phones, by scrolling or adjusting columns as needed. To make a responsive table in CSS, place it inside a <div> with overflow-x: auto;. This lets the table scroll sideways on sm
3 min read
How to hide elements in responsive layout using CSS ?
CSS provides powerful tools to create responsive websites that adapt to different screen sizes and devices. One of the key techniques for creating responsive designs is media queries, introduced in CSS3. Media queries allow you to apply styles based on the characteristics of the device, such as its
3 min read
HTML | DOM Style width Property
The Style width property in HTML DOM is used to set or return the width of an element which can be block-level elements or elements with fixed position. Syntax: It is used to return the width property:object.style.widthIt is used to set the width property:object.style.width = "auto|length|%|initial|
2 min read
Primer CSS Responsive Padding
Primer CSS is a free open-source CSS framework built on systems that lay the groundwork for basic style elements like spacing, typography, and color. Our patterns are both stable and interoperable because of their systematic structure. Object-Oriented CSS principles, core CSS, and BEM architecture i
3 min read
CSS min-height Property
The min-height property in CSS is used to set the minimum height of an element. The min-height property is used when the content of the element is smaller than the min-height and if the content is larger than the min-height then it has no effect. This property ensures that the value of the height pr
3 min read
How to Create Equal Height Columns in CSS ?
Equal Height Columns in CSS refer to ensuring that multiple columns in a layout have the same height, regardless of the content inside each column. This can be achieved using modern CSS techniques like Flexbox, CSS Grid, or the Table display property. Table of Content Using FlexUsing GridUsing Table
3 min read
HTML | DOM Style height Property
HTML DOM Style height Property is similar to CSS Height Property but it is used to set or get height of an element dynamically. Syntax : To set the height property : object.style.height = auto|length|%|initial|inherit;To get height property value: object.style.height Property Values: ValueDescriptio
2 min read