.dump()

The .dump() function encodes a Python object as a JSON file. The encoding conversion is based on the following table. The .dumps() function, alternatively, takes a Python object and returns a JSON string.

Syntax

json.dump(py_obj, file_name)

json.dumps(py_obj)

A py_obj can be a string, list, dictionary, etc.

Example

The .dump() function can be used to convert a Python object to a JSON file:

import json
import string
letters = string.ascii_lowercase
with open('alphabet.json', 'w') as outfile:
json.dump(letters, outfile)

Codebyte Example

The json library can be used to encode and decode a Python dictionary:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Python on Codecademy