Python JSON dump function converts the objects into appropriate JSON objects. It is used to write Python serialized objects as JSON formatted data into a file.
json.dump(object, skipkeys=False, ensure_ascii=True, indent=None, allow_nan=True, number_mode = None, datetime_mode = None, separators=None)
obj
is nothing but a Python serializable object which you want to convert into a JSON format.- A
fp
is a file pointer used to write JSON-formatted data into a file? Python json module always produces string objects, not bytes objects, therefore,fp.write()
must support string input. - 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 aTypeError
. For example, if one of your dictionary keys is a custom Python object, that key will be omitted while converting the dictionary into JSON. - If
ensure_ascii
is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. Ifensure_ascii
is false, these characters will be output as-is. allow_nan
is True by default so their JavaScript equivalents (NaN, Infinity, -Infinity) will be used. If False it will be a ValueError to serialize out-of-range float values (nan, inf, -inf).- An
indent
the argument is used to pretty-print JSON to make it more readable. The default is(', ', ': ')
. To get the most compact JSON representation, you should use(',', ':')
to eliminate whitespace. - If
sort_keys
is true (default: False), then the output of dictionaries will be sorted by key
Python JSON dump function example
A simple example code converted the python dictionary to json file format using the JSON package.
import json
dict_pets = {
"Dog": {
"Species": "cocker spaniel",
"country": "United Kingdom"
},
"Cat": {
"Species": "British Shorthair",
"country": "United Kingdom"
},
"Hamster": {
"Species": "golden hamster ",
"country": "Turkey"
}
}
pets_data = open("pet_data.json", "w")
json.dump(dict_pets, pets_data)
Output:
The json.dump()
is used for following operations
- Encode Python serialized objects as JSON formatted data.
- Encode and write Python objects into a JSON file
- PrettyPrinted JSON data
- Skip nonbasic types while JSON encoding
- Perform compact encoding to save file space
- Handle non-ASCII data while encoding JSON
Mapping between JSON and Python entities while Encoding
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int & float-derived Enums | number |
True | true |
False | false |
None | null |
Do comment if you have any doubts or suggestions on this Python JSON topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.