PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » JSON » Python JSON dump() and dumps() for JSON Encoding

Python JSON dump() and dumps() for JSON Encoding

Updated on: May 14, 2021 | 9 Comments

In this article, You will learn how to use the Python json module to write Python serialized objects as JSON formatted data into file and string. The json module provides the following two methods to encode Python objects into JSON format.

  • The json.dump() method (without “s” in “dump”) used to write Python serialized object as JSON formatted data into a file.
  • The json.dumps() method encodes any Python object into JSON formatted String.

Further Reading:

  • Solve Python JSON Exercise to practice Python JSON skills

The json.dump() and  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
Python JSON Encoding and serialization using dump and dumps
Python JSON Encoding and serialization using dump and dumps

Syntax of json.dump() and json.dumps()

You can do many things using json.dump() and json.dumps() method. Let’s understand the different parameters of json.dump() to achieve different results.

Syntax of json.dump()

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Use: It is used to write a Python object into a file as a JSON formatted data.

Syntax of json.dumps()

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)

Use: It is used to write a Python object into a JSON String.

Parameters used:

  • 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 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 a TypeError. 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. If ensure_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 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

json.dumps() to convert Python primitive types into JSON equivalent

There are multiple scenarios where you need to use serialized JSON data in your program. If you need this serialized JSON data in your application of further processing then you can convert it to a native Python str object instead of writing it in a file.

For example, you receive an HTTP request to send developer detail. you fetched developer data from the database table and store it in a Python dictionary or any Python object, Now you need to send that data back to the requested application so you need to convert the Python dictionary object into a JSON formatted string to send as a response in JSON string. To do this you need to use json.dumps().

The json.dumps() returns the JSON string representation of the Python dict. Let see the example now.

Example: Convert Python dictionary into a JSON formatted String

import json

def SendJsonResponse(resultDict):
    print("Convert Python dictionary into JSON formatted String")
    developer_str = json.dumps(resultDict)
    print(developer_str)

# sample developer dict
developer_Dict = {
    "name": "Jane Doe",
    "salary": 9000,
    "skills": ["Python", "Machine Learning", "Web Development"],
    "email": "jane.doe@pynative.com"
}
SendJsonResponse(developer_Dict)

Output:

Writing JSON data into a Python String
{"name": "Jane Doe", "salary": 9000, "skills": ["Python", "Machine Learning", "Web Development"], "email": "jane.doe@pynative.com"}

Mapping between JSON and Python entities while Encoding

To encode Python objects into JSON equivalent json module uses the following conversion table. The json.dump() and json.dumps() the method performs the translations when encoding.

Now let’s see how to convert all Python primitive types such as a dict, list, set, tuple, str, numbers into JSON formatted data. Please refer to the following table to know the mapping between JSON and Python data types.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int & float-derived Enumsnumber
Truetrue
Falsefalse
Nonenull
Mapping between JSON and Python data types

Let see the example now.

import json

sampleDict = {
    "colorList": ["Red", "Green", "Blue"],
    "carTuple": ("BMW", "Audi", "range rover"),
    "sampleString": "pynative.com",
    "sampleInteger": 457,
    "sampleFloat": 225.48,
    "booleantrue": True,
    "booleanfalse": False,
    "nonevalue": None
}
print("Converting Python primitive types into JSON")
resultJSON = json.dumps(sampleDict)
print("Done converting Python primitive types into JSON")
print(resultJSON)

Output:

Converting Python primitive types into JSON
Done converting Python primitive types into JSON
{"colorList": ["Red", "Green", "Blue"], "carTuple": ["BMW", "Audi", "range rover"], "sampleString": "pynative.com", "sampleInteger": 457, "sampleFloat": 225.48, "booleantrue": true, "booleanfalse": false, "nonevalue": null}

json.dump() to encode and write JSON data to a file

We can use it in the following cases.

  • To write the JSON response in a file: Most of the time, when you execute a GET request, you receive a response in JSON format, and you can store JSON response in a file for future use or for an underlying system to use.
  • For example, you have data in a list or dictionary or any Python object, and you want to encode and store it in a file in the form of JSON.

In this example, we are going to convert the Python dictionary into a JSON format and write it into a file.

import json

# assume you have the following dictionary
developer = {
    "name": "jane doe",
    "salary": 9000,
    "email": "JaneDoe@pynative.com"
}
print("Started writing JSON data into a file")
with open("developer.json", "w") as write_file:
    json.dump(developer, write_file) # encode dict into JSON
print("Done writing JSON data into .json file")

Output:

Started writing JSON data into a file
Done writing JSON data into developerDetail.json file
File after writing JSON encoded data using Python
File after writing JSON encoded data using Python

Write Indented and pretty printed JSON data into a file

If the user wants to read a JSON file so it must be readable and well organized, so whoever consumes this will have a better understanding of a structure of a data. The dump() method provides the following arguments to pretty-print JSON data.

  • The indent parameter specifies the spaces that are used at the beginning of a line.
  • The separator argument of a json.dump method you can specify any separator between key and value.
  • The sort_keys to sort JSON data by keys.

Let’s see how to write pretty-printed JSON data into a file.

import json

developer = {
    "name": "jane doe",
    "salary": 9000,
    "skills": ["Raspberry pi", "Machine Learning", "Web Development"],
    "email": "JaneDoe@pynative.com"
}

with open("developerPrettyPrint.json", "w") as write_file:
    json.dump(developer, write_file, indent=4, separators=(", ", ": "), sort_keys=True)
print("Done writing pretty printed JSON data into a file")

Output:

Done writing pretty printed JSON data into a file
File after writing prettyprinted JSON data
File after writing prettyprinted JSON data

Read: Complete Guide on JSON PrettyPrinting in Python

Compact encoding to save file space by changing JSON key-value separator

If you are not reading a file, but you only need to write JSON data into a file to use by the underlying system or application, then you can write JSON data into a file by doing compact encoding.

We can write JSON data into a file by changing the JSON key-value separator. You can change JSON representation as per your needs. Using the separator argument of a json.dump() method you can specify any separator between key and value.

To limit the JSON file size we can remove extra spacing between JSON key-value. I have decided to do the compact encoding (separators=(',', ':')). Using this separator we can remove the whitespaces from JSON to make the JSON more compact and save bytes from being sent via HTTP. Now, Let see the example.

import json

developer_dict = {
    "name": "jane doe",
    "salary": 9000,
    "skills": ["Raspberry pi", "Machine Learning", "Web Development"],
    "companies": ["Google", "Facebook", "IBM"],
    "email": "JaneDoe@pynative.com"
}

print("Started writing compact JSON data into a file")
with open("developerDetailCompact.json", "w") as write_file:
    json.dump(developer_dict, write_file, separators=(',', ':'))
print("Done writing compact JSON data into json file")

Output:

Started writing compact JSON data into a file
Done writing compact JSON data into .json file

File content:

{"name":"jane doe","salary":9000,"skills":["Raspberry pi","Machine Learning","Web Development"],"companies":["Google","Facebook","IBM"],"email":"JaneDoe@pynative.com"}

Skip nonbasic types while writing JSON into a file using skipkeys parameter

The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent (e.g., dictionary, lists, strings, ints, None, etc.).

If the Python dictionary contains a custom Python object as one of the keys and if we try to convert it into a JSON format, you will get a TypeError i.e., Object of type "Your Class" is not JSON serializable.

If this custom object isn’t required in JSON data, you can skip it using a skipkeys=true argument of the json.dump() method.
If skipkeys=true is True, then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If it is necessary to convert it into JSON, then you can refer to our article on how to Make Python class JSON Serializable.

Now, Let’s see the example.

import json

class PersonalInfo:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def showInfo(self):
        print("Developer name is " + self.name, "Age is ", self.age)

dev = PersonalInfo("John", 36)
developer_Dict = {
    PersonalInfo: dev,
    "salary": 9000,
    "skills": ["Python", "Machine Learning", "Web Development"],
    "email": "jane.doe@pynative.com"
}
print("Writing JSON data into file by skipping non-basic types")
with open("developer.json", "w") as write_file:
    json.dump(developer_Dict, write_file, skipkeys=True)
print("Done")

Output:

Writing JSON data into file by skipping non-basic types
Done
JSON file after skipping on-basic types
JSON file after skipping on-basic types

As you can see in the JSON output the PersonalInfo object is skipped.

Handle non-ASCII characters from JSON data while writing it into a file

The json.dump() method has ensure_ascii parameter. The ensure_ascii is by-default true. The output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is. If you want to store non-ASCII characters, as-is use the following code.

import json

unicode_string = u"\u00f8"
print("unicode String is ", unicode_string)

# set ensure_ascii=False
print("JSON character encoding by setting ensure_ascii=False")
print(json.dumps(unicode_string, ensure_ascii=False))

Output:

unicode String is  ø
JSON character encoding by setting ensure_ascii=False
"ø"

Also, read the Complete Guide on Encode and Decode Unicode data into JSON using Python.

Next Steps

I want to hear from you. What do you think of this article? Or maybe I missed one of the uses of json.dump() and json.dumps(). Either way, let me know by leaving a comment below.

Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.

Filed Under: Python, Python JSON

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python JSON

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python JSON
TweetF  sharein  shareP  Pin

  Python JSON

  • Python JSON Guide
  • JSON Serialization
  • JSON Parsing
  • JSON Validation
  • PrettyPrint JSON
  • Make Python Class JSON serializable
  • Convert JSON Into Custom Python Object
  • Python JSON Unicode
  • Parse JSON using Python requests
  • Post JSON using Python requests
  • Serialize DateTime into JSON
  • Serialize Python Set into JSON
  • Serialize NumPy array into JSON
  • Parse multiple JSON objects from file
  • Parse Nested JSON
  • Python JSON Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2022 pynative.com