python dictionary to json

Converting Python Dictionary to JSON

JSON(JavaScript Object Notation) is a lightweight data exchange format that is easy for humans to read and write and easy for machines to parse and generate. It is used to store and transfer data between different programming languages. Python provides a built-in module named "json" that allows us to convert Python dictionary to JSON data format.

Using json.dumps()

The json.dumps() method converts Python dictionary to JSON format. The method takes a dictionary as input and returns a JSON string.


import json

python_dict = {
  "name": "Raju",
  "age": 25,
  "city": "New York"
}

# Convert python dictionary to JSON string
json_string = json.dumps(python_dict)

print(json_string)

The output will be:


{
  "name": "Raju",
  "age": 25,
  "city": "New York"
}

Using json.dump()

The json.dump() method converts Python dictionary to a JSON file. The method takes a dictionary and file object as input and writes the JSON data to the file.


import json

python_dict = {
  "name": "Raju",
  "age": 25,
  "city": "New York"
}

# Convert python dictionary to JSON file
with open('data.json', 'w') as file:
    json.dump(python_dict, file)

Using custom encoder while converting complex object to JSON

Sometimes we may have complex objects like datetime or numpy arrays in a dictionary. In that case, we need to write a custom encoder to convert it to JSON format.


import json
import numpy as np
from datetime import datetime

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        else:
            return json.JSONEncoder.default(self, obj)

python_dict = {
  "name": "Raju",
  "age": 25,
  "city": "New York",
  "created_at": datetime.utcnow(),
  "data": np.random.rand(3,3)
}

# Convert python dictionary with custom encoder to JSON string
json_string = json.dumps(python_dict, cls=CustomEncoder)

print(json_string)

The output will be:


{
  "name": "Raju",
  "age": 25,
  "city": "New York",
  "created_at": "2021-08-24 06:30:30",
  "data": [
    [0.5224247307828228, 0.1427551526254654, 0.6792291179721656],
    [0.9039499230428048, 0.8602094457297024, 0.14543315891451495],
    [0.09426199132354735, 0.06236929426917092, 0.10228541352090177]
  ]
}

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe