Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • Python Tutorial
    • Data Types
    • Interview Questions
    • Examples
    • Quizzes
    • DSA Python
    • Data Science
    • NumPy
    • Pandas
    • Practice
    • Django
    • Flask
    • Projects
    Open In App

    Encoding and Decoding Custom Objects in Python-JSON

    Last Updated : 15 Jul, 2025
    Comments
    Improve
    Suggest changes
    5 Likes
    Like
    Report
    JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For more information, refer to Read, Write and Parse JSON using Python

    Getting Started

    Python provides a built-in json library to deal with JSON objects. All you need is to import the JSON module using the following line in your Python program and start using its functionality.
    import json
    Now the JSON module provides a lot of functionality and we're going to discuss only 2 methods out of them. They are dumps and loads. The process of converting a python object to a json one is called JSON serialization or encoding and the reverse process i.e. converting json object to Python one is called deserialization or decoding For encoding, we use json.dumps() and for decoding, we'll use json.loads(). So it is obvious that the dumps method will convert a python object to a serialized JSON string and the loads method will parse the Python object from a serialized JSON string. Note:
    • It is worth mentioning here that the JSON object which is created during serialization is just a Python string, that's why you'll find the terms "JSON object" and "JSON string" used interchangeably in this article
    • Also it is important to note that a JSON object corresponds to a Dictionary in Python. So when you use loads method, a Python dictionary is returned by default (unless you change this behaviour as discussed in the custom decoding section of this article)
    Example: Python3 1==
    import json
    
    # A basic python dictionary
    py_object = {"c": 0, "b": 0, "a": 0} 
    
    # Encoding
    json_string = json.dumps(py_object)
    print(json_string)
    print(type(json_string))
    
    # Decoding JSON
    py_obj = json.loads(json_string) 
    print()
    print(py_obj)
    print(type(py_obj))
    
    Output:
    {"c": 0, "b": 0, "a": 0}
    <class 'str'>
    
    {'c': 0, 'b': 0, 'a': 0}
    <class 'dict'>
    Although what we saw above is a very simple example. But have you wondered what happens in the case of custom objects? In that case he above code will not work and we will get an error something like - TypeError: Object of type SampleClass is not JSON serializable. So what to do? Don't worry we will get to get in the below section.

    Encoding and Decoding Custom Objects

    In such cases, we need to put more efforts to make them serialize. Let's see how we can do that. Suppose we have a user-defined class Student and we want to make it JSON serializable. The simplest way of doing that is to define a method in our class that will provide the JSON version of our class' instance. Example: Python3 1==
    import json
     
    class Student:
        def __init__(self, name, roll_no, address):
            self.name = name
            self.roll_no = roll_no
            self.address = address
     
        def to_json(self):
            '''
            convert the instance of this class to json
            '''
            return json.dumps(self, indent = 4, default=lambda o: o.__dict__)
     
    class Address:
        def __init__(self, city, street, pin):
            self.city = city
            self.street = street
            self.pin = pin
            
    address = Address("Bulandshahr", "Adarsh Nagar", "203001")
    student = Student("Raju", 53, address)
    
    # Encoding
    student_json = student.to_json()
    print(student_json)
    print(type(student_json))
    
    # Decoding
    student = json.loads(student_json)
    print(student)
    print(type(student))
    
    Output:
    { "name": "Raju", "roll_no": 53, "address": { "city": "Bulandshahr", "street": "Adarsh Nagar", "pin": "203001" } } <class 'str'> {'name': 'Raju', 'roll_no': 53, 'address': {'city': 'Bulandshahr', 'street': 'Adarsh Nagar', 'pin': '203001'}} <class 'dict'>
    Another way of achieving this is to create a new class that will extend the JSONEncoder and then using that class as an argument to the dumps method. Example: Python3 1==
    import json
    from json import JSONEncoder
    
    class Student:
        def __init__(self, name, roll_no, address):
            self.name = name
            self.roll_no = roll_no
            self.address = address
    
    
    class Address:
        def __init__(self, city, street, pin):
            self.city = city
            self.street = street
            self.pin = pin
    
    class EncodeStudent(JSONEncoder):
            def default(self, o):
                return o.__dict__
                
    address = Address("Bulandshahr", "Adarsh Nagar", "203001")
    student = Student("Raju", 53, address)
    
    # Encoding custom object to json
    # using cls(class) argument of
    # dumps method
    student_JSON = json.dumps(student, indent = 4,
                              cls = EncodeStudent)
    print(student_JSON)
    print(type(student_JSON))
    
    # Decoding
    student = json.loads(student_JSON)
    print()
    print(student)
    print(type(student))
    
    Output:
    { "name": "Raju", "roll_no": 53, "address": { "city": "Bulandshahr", "street": "Adarsh Nagar", "pin": "203001" } } <class 'str'> {'name': 'Raju', 'roll_no': 53, 'address': {'city': 'Bulandshahr', 'street': 'Adarsh Nagar', 'pin': '203001'}} <class 'dict'>
    For Custom Decoding, if we want to convert the JSON into some other Python object (i.e. not the default dictionary) there is a very simple way of doing that which is using the object_hook parameter of the loads method. All we need to do is to define a method that will define how do we want to process the data and then send that method as the object_hook argument to the loads method, see in given code. Also, the return type of load will no longer be the Python dictionary. Whatever is the return type of the method we'll pass in as object_hook, it will also become the return type of loads method. This means that in following example, complex number will be the return type. Python3 1==
    import json
    
    
    def as_complex(dct):
        
        if '__complex__' in dct:
            return complex(dct['real'], dct['imag'])
        
        return dct
    
    res = json.loads('{"__complex__": true, "real": 1, "imag": 2}',
               object_hook = as_complex)
    print(res)
    print(type(res))
    
    Output:
    (1+2j)
    <class 'complex'>
    Create Quiz

    V

    vinayj
    Improve

    V

    vinayj
    Improve
    Article Tags :
    • Python
    • Python-json

    Explore

      Python Fundamentals

      Python Introduction

      2 min read

      Input and Output in Python

      4 min read

      Python Variables

      4 min read

      Python Operators

      4 min read

      Python Keywords

      2 min read

      Python Data Types

      8 min read

      Conditional Statements in Python

      3 min read

      Loops in Python - For, While and Nested Loops

      5 min read

      Python Functions

      5 min read

      Recursion in Python

      4 min read

      Python Lambda Functions

      5 min read

      Python Data Structures

      Python String

      5 min read

      Python Lists

      4 min read

      Python Tuples

      4 min read

      Python Dictionary

      3 min read

      Python Sets

      6 min read

      Python Arrays

      7 min read

      List Comprehension in Python

      4 min read

      Advanced Python

      Python OOP Concepts

      11 min read

      Python Exception Handling

      5 min read

      File Handling in Python

      4 min read

      Python Database Tutorial

      4 min read

      Python MongoDB Tutorial

      3 min read

      Python MySQL

      9 min read

      Python Packages

      10 min read

      Python Modules

      3 min read

      Python DSA Libraries

      15 min read

      List of Python GUI Library and Packages

      3 min read

      Data Science with Python

      NumPy Tutorial - Python Library

      3 min read

      Pandas Tutorial

      4 min read

      Matplotlib Tutorial

      5 min read

      Python Seaborn Tutorial

      3 min read

      StatsModel Library - Tutorial

      3 min read

      Learning Model Building in Scikit-learn

      6 min read

      TensorFlow Tutorial

      2 min read

      PyTorch Tutorial

      6 min read

      Web Development with Python

      Flask Tutorial

      8 min read

      Django Tutorial | Learn Django Framework

      7 min read

      Django ORM - Inserting, Updating & Deleting Data

      4 min read

      Templating With Jinja2 in Flask

      6 min read

      Django Templates

      5 min read

      Build a REST API using Flask - Python

      3 min read

      Building a Simple API with Django REST Framework

      3 min read

      Python Practice

      Python Quiz

      1 min read

      Python Coding Practice

      1 min read

      Python Interview Questions and Answers

      15+ min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.
See More

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences