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

    Working With JSON Data in Python

    Last Updated : 11 Jul, 2025
    Comments
    Improve
    Suggest changes
    19 Likes
    Like
    Report
    See More

    JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python. JSON shows an API similar to users of Standard Library marshal and pickle modules and Python natively supports JSON features. For example:  

    Python3
    # Python program showing 
    # use of json package
    
    import json
    
    # {key:value mapping}
    a ={"name":"John",
       "age":31,
        "Salary":25000}
    
    # conversion to JSON done by dumps() function
     b = json.dumps(a)
    
    # printing the output
    print(b)
    

    Output: 

    {"age": 31, "Salary": 25000, "name": "John"}

    As you can see, JSON supports primitive types, like strings and numbers, as well as nested lists, tuples, and objects  

    Python3
    # Python program showing that
    # json support different primitive
    # types
    
    import json
    
    # list conversion to Array
    print(json.dumps(['Welcome', "to", "GeeksforGeeks"]))
    
    # tuple conversion to Array
    print(json.dumps(("Welcome", "to", "GeeksforGeeks")))
    
    # string conversion to String
    print(json.dumps("Hi"))
    
    # int conversion to Number
    print(json.dumps(123))
    
    # float conversion to Number
    print(json.dumps(23.572))
    
    # Boolean conversion to their respective values
    print(json.dumps(True))
    print(json.dumps(False))
    
    # None value to null
    print(json.dumps(None))
    

    Output: 

    ["Welcome", "to", "GeeksforGeeks"]
    ["Welcome", "to", "GeeksforGeeks"]
    "Hi"
    123
    23.572
    true
    false
    null

    Serializing JSON: 

    The process of encoding JSON is usually called serialization. This term refers to the transformation of data into a series of bytes (hence serial) to be stored or transmitted across a network. To handle the data flow in a file, the JSON library in Python uses dump() function to convert the Python objects into their respective JSON object, so it makes it easy to write data to files. See the following table given below.  

    Python objectJSON object
    dictobject
    list, tuplearray
    strstring
    int, long, floatnumbers
    Truetrue
    Falsefalse
    Nonenull

    Example: Serialization  

    Consider the given example of a Python object.

    Python3
    var = { 
          "Subjects": {
                      "Maths":85,
                      "Physics":90
                       }
          }
    

    Using Python's context manager, create a file named Sample.json and open it with write mode. 

    Python3
    with open("Sample.json", "w") as p:
         json.dump(var, p)
    

    Here, the dump() takes two arguments first, the data object to be serialized, and second the object to which it will be written(Byte format). 

    Deserializing JSON:

    Deserialization is the opposite of Serialization, i.e. conversion of JSON objects into their respective Python objects. The load() method is used for it. If you have used JSON data from another program or obtained it as a string format of JSON, then it can easily be deserialized with load(), which is usually used to load from a string, otherwise, the root object is in a list or dict. 

    Python3
    with open("Sample.json", "r") as read_it:
         data = json.load(read_it)
    

    Example: Deserialization 

    Python3
    json_var ="""
    {
        "Country": {
            "name": "INDIA",
            "Languages_spoken": [
                {
                    "names": ["Hindi", "English", "Bengali", "Telugu"]
                }
            ]
        }
    }
    """
    var = json.loads(json_var)
    

    Encoding and Decoding: 

    Encoding is defined as converting the text or values into an encrypted form that can only be used by the desired user through decoding it. Here encoding and decoding is done for JSON (object)format. Encoding is also known as Serialization and Decoding is known as Deserialization. Python has a popular package for this operation. This package is known as Demjson. To install it follow the steps below. 

    For Windows: 

    pip install demjson

    For Ubuntu:

     sudo apt-get update
     sudo apt-get install python-demjson

    Encoding: The encode() function is used to convert the python object into a JSON string representation.

    Syntax:  

    demjson.encode(self, obj, nest_level=0) 

    Example 1: Encoding using demjson package. 

    Python3
    # storing marks of 3 subjects
    var = [{"Math": 50, "physics":60, "Chemistry":70}]
    print(demjson.encode(var))
    

    Output: 

    [{"Chemistry":70, "Math":50, "physics":60}]

    Decoding: The decode() function is used to convert the JSON object into python-format type. 

    Syntax:

    demjson.decode(self, obj)

    Example 2: Decoding using demjson package 

    Python3
    var = '{"a":0, "b":1, "c":2, "d":3, "e":4}'
    text = demjson.decode(var)
    

    Output: 

    {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

    Example 3: Encoding using iterencode package  

    Python3
    # Other Method of Encoding
    json.JSONEncoder().encode({"foo": ["bar"]})
    '{"foo": ["bar"]}'
    
    # Using iterencode(object) to encode a given object.
    for i in json.JSONEncoder().iterencode(bigobject):
        mysocket.write(i)
    

    Example 4: Encoding and Decoding using dumps() and loads().

    Python3
    # To encode and decode operations
    import json
    var = {'age':31, 'height':6}
    x = json.dumps(var)
    y = json.loads(x)
    print(x)
    print(y)
    
    # when performing from a file in disk
    with open("any_file.json", "r") as readit:
        x = json.load(readit)
    print(x)
    

    Command-Line Usage

    The JSON library can also be used from the command-line, to validate and pretty-print your JSON.

    $ echo "{ \"name\": \"Monty\", \"age\": 45 }"

    Searching through JSON with JMESPath

    JMESPath is a query language for JSON. It allows you to easily obtain the data you need from a JSON document. If you ever worked with JSON before, you probably know that it's easy to get a nested value. For example, doc["person"]["age"] will get you the nested value for age in a document.

    First, install jmespath : 

    $ pip3 install jmespath

    Real-World Example: 

    Let us take a real-life example of the implementation of the JSON in python. A good source for practice purposes is JSON_placeholder, it provides a great API requests package which we will be using in our example. To get started, follow these simple steps. Open Python IDE or CLI and create a new script file, name it sample.py. 

    Python3
    import requests
    import json
    
    # Now we have to request our JSON data through
    # the API package
    res = requests.get("https://jsonplaceholder.typicode.com/ / todos")
    var = json.loads(res.text)
    
    # To view your Json data, type var and hit enter
    var
    
    # Now our Goal is to find the User who have 
    # maximum completed their task !!
    # i.e we would count the True value of a 
    # User in completed key.
    # {
        # "userId": 1,
        # "id": 1,
        # "title": "Hey",
        # "completed": false,  # we will count
                               # this for a user.
    # }
    
    # Note that there are multiple users with 
    # unique id, and their task have respective
    # Boolean Values.
    
    def find(todo):
        check = todo["completed"]
        max_var = todo["userId"] in users
        return check and max_var
    
    # To find the values.
    
    Value = list(filter(find, todos))
    
    # To write these value to your disk
    
    with open("sample.json", "w") as data:
        Value = list(filter(keep, todos))
        json.dump(Value, data, indent = 2)
    

    To know more, Click Here

    Create Quiz

    K

    kartikeya shukla 1
    Improve

    K

    kartikeya shukla 1
    Improve
    Article Tags :
    • Python

    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.

What kind of Experience do you want to share?

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