Skip to main content
json Dump Python With Example

json Dump Python With Example

Here, you’ll learn how to use the Python json module to save Python serialized objects as JSON formatted data to a file or a string using the Python JSON module. We’ll discuss python dump method here.

The JSON module has two methods for converting Python objects to JSON format:

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

Checkout other recommendable tutorials:

The above methods will help to do following operations:

  • Python serialised objects are encoded as JSON structured data.
  • Write Python objects to a JSON file by encoding and decoding them.
  • PrettyPrinted JSON data
  • Skip nonbasic types while JSON encoding
  • Perform compact encoding to save file space
  • Handle non-ASCII data while encoding JSON

json.dump() method

The json.dump() method is used to write a Python object into a file as JSON formatted data.

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)

json.dumps() method

The json.dumps() method is used to write a Python object into a JSON String..

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)

Parameters:

  • obj : This is a Python serializable object which you want to convert into a JSON format.
  • fp: Thiis is a file pointer used to write JSON formatted data into file.
  • skipkeys (default: False): when it true 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 (default: True): The result will have all incoming non-ASCII characters escaped. If false, these characters will be output as-is.
  • allow_nan (default: True): 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).
  • indent : It’s used to pretty-print JSON to make it more readable.
  • sort_keys (default: False) : The output of dictionaries will be sorted by key if its set to True

How To Use json.dump() method

Let’s convert Python dictionary into a JSON formatted String using json.dumps() method.

import json

# sample dict
test_Dict = {
    "name": "Adam",
    "age": 40,
    "salary": 5400
}
js_str = json.dumps(test_Dict)
print(js_str)

Output:

{"name": "Adam", "age": 40, "salary": 5400}

json dump To file Using json.dump() method

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

import json

sampleDict = {
    "name": "Adam",
    "age": 40,
    "salary": 5400
}

with open("employee.json", "w") as write_file:
    json.dump(sampleDict, write_file) # encode dict into JSON
print("Done writing JSON data into .json file")

Output:

Done writing JSON data into .json file

Leave a Reply

Your email address will not be published. Required fields are marked *