Skip to content
the poor coder

python dictionary to json

Poor Man
Published
Reading time
2 min read
On this page

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.

Text

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:

Text

{
  "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.

Text

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.

Text

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:

Text

{
  "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]
  ]
}

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC