PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python JSON Exercise

Python JSON Exercise

Updated on: December 8, 2021 | 9 Comments

This Python JSON exercise helps Python developers to practice JSON creation, manipulation, and parsing. As you know, JSON (an acronym for JavaScript Object Notation) is a data-interchange format and is commonly used for client-server communication.

Read Python JSON tutorials for any help.

This exercise includes the following: –

  • It has 9 questions and solutions provided for each question.
  • Each question includes a specific JSON concept you need to learn. When you complete each question, you get more familiar with JSON encoding and decoding in Python.

Use Online Code Editor to solve exercise questions.

Table of contents

  • Exercise 1: Convert the following dictionary into JSON format
  • Exercise 2: Access the value of key2 from the following JSON
  • Exercise 3: PrettyPrint following JSON data
  • Exercise 4: Sort JSON keys in and write them into a file
  • Exercise 5: Access the nested key ‘salary’ from the following JSON
  • Exercise 6: Convert the following Vehicle Object into JSON
  • Exercise 7: Convert the following JSON into Vehicle Object
  • Exercise 8: Check whether following json is valid or invalid. If Invalid correct it
  • Exercise 9: Parse the following JSON to get all the values of a key ‘name’ within an array

Exercise 1: Convert the following dictionary into JSON format

data = {"key1" : "value1", "key2" : "value2"}Code language: Python (python)

Expected Output:

data = {"key1" : "value1", "key2" : "value2"}
Show Solution
import json

data = {"key1" : "value1", "key2" : "value2"}

jsonData = json.dumps(data)
print(jsonData)Code language: Python (python)

Exercise 2: Access the value of key2 from the following JSON

import json

sampleJson = """{"key1": "value1", "key2": "value2"}"""
# write code to print the value of key2Code language: Python (python)

Expected Output:

value2
Show Solution
import json

sampleJson = """{"key1": "value1", "key2": "value2"}"""

data = json.loads(sampleJson)
print(data['key2'])Code language: Python (python)

Exercise 3: PrettyPrint following JSON data

PrettyPrint following JSON data with indent level 2 and key-value separators should be (",", " = ").

sampleJson = {"key1": "value1", "key2": "value2"}Code language: Python (python)

Expected Output:

{
  "key1" = "value2",
  "key2" = "value2",
  "key3" = "value3"
}
Show Solution
import json

sampleJson = {"key1" : "value2", "key2" : "value2", "key3" : "value3"}
prettyPrintedJson  = json.dumps(sampleJson, indent=2, separators=(",", " = "))
print(prettyPrintedJson)
Code language: Python (python)

Exercise 4: Sort JSON keys in and write them into a file

Sort following JSON data alphabetical order of keys

sampleJson = {"id" : 1, "name" : "value2", "age" : 29}Code language: Python (python)

Expected Output:

{
    "age": 29,
    "id": 1,
    "name": "value2"
}
Show Solution
import json

sampleJson = {"id" : 1, "name" : "value2", "age" : 29}

print("Started writing JSON data into a file")
with open("sampleJson.json", "w") as write_file:
    json.dump(sampleJson, write_file, indent=4, sort_keys=True)
print("Done writing JSON data into a file")Code language: Python (python)

Exercise 5: Access the nested key ‘salary’ from the following JSON

import json

sampleJson = """{ 
   "company":{ 
      "employee":{ 
         "name":"emma",
         "payble":{ 
            "salary":7000,
            "bonus":800
         }
      }
   }
}"""

# write code to print the value of salaryCode language: Python (python)

Expected Output:

7000
Show Solution
import json

sampleJson = """{ 
   "company":{ 
      "employee":{ 
         "name":"emma",
         "payble":{ 
            "salary":7000,
            "bonus":800
         }
      }
   }
}"""

data = json.loads(sampleJson)
print(data['company']['employee']['payble']['salary'])
Code language: Python (python)

Exercise 6: Convert the following Vehicle Object into JSON

import json

class Vehicle:
    def __init__(self, name, engine, price):
        self.name = name
        self.engine = engine
        self.price = price

vehicle = Vehicle("Toyota Rav4", "2.5L", 32000)

# Convert it into JSON formatCode language: Python (python)

Expected Output:

{
    "name": "Toyota Rav4",
    "engine": "2.5L",
    "price": 32000
}
Show Solution
import json
from json import JSONEncoder

class Vehicle:
    def __init__(self, name, engine, price):
        self.name = name
        self.engine = engine
        self.price = price

class VehicleEncoder(JSONEncoder):
        def default(self, o):
            return o.__dict__

vehicle = Vehicle("Toyota Rav4", "2.5L", 32000)

print("Encode Vehicle Object into JSON")
vehicleJson = json.dumps(vehicle, indent=4, cls=VehicleEncoder)
print(vehicleJson)Code language: Python (python)

Exercise 7: Convert the following JSON into Vehicle Object

{ "name": "Toyota Rav4", "engine": "2.5L", "price": 32000 }

For example, we should be able to access Vehicle Object using the dot operator like this.

vehicleObj.name, vehicleObj.engine, vehicleObj.price
Show Solution
import json

class Vehicle:
    def __init__(self, name, engine, price):
        self.name = name
        self.engine = engine
        self.price = price

def vehicleDecoder(obj):
        return Vehicle(obj['name'], obj['engine'], obj['price'])

vehicleObj = json.loads('{ "name": "Toyota Rav4", "engine": "2.5L", "price": 32000 }',
           object_hook=vehicleDecoder)

print("Type of decoded object from JSON Data")
print(type(vehicleObj))
print("Vehicle Details")
print(vehicleObj.name, vehicleObj.engine, vehicleObj.price)Code language: Python (python)

Exercise 8: Check whether following json is valid or invalid. If Invalid correct it

{ 
   "company":{ 
      "employee":{ 
         "name":"emma",
         "payble":{ 
            "salary":7000
            "bonus":800
         }
      }
   }
}
Show Solution

Solution 1:

Python provides The json.tool module to validate JSON objects from the command line. Run the following command.

Command: echo "JSON DATA" | python -m json.tool

echo { "company":{ "employee":{ "name":"emma", "payble":{ "salary":7000 "bonus":800} } } } | python -m json.tool
Code language: Python (python)

Output:

Expecting ',' delimiter: line 1 column 68 (char 67)

Just add ',' after "salary":7000 to solve the error.

Solution 2

import json

def validateJSON(jsonData):
    try:
        json.loads(jsonData)
    except ValueError as err:
        return False
    return True

InvalidJsonData = """{ "company":{ "employee":{ "name":"emma", "payble":{ "salary":7000 "bonus":800} } } }"""
isValid = validateJSON(InvalidJsonData)

print("Given JSON string is Valid", isValid)Code language: Python (python)

Exercise 9: Parse the following JSON to get all the values of a key ‘name’ within an array

[ 
   { 
      "id":1,
      "name":"name1",
      "color":[ 
         "red",
         "green"
      ]
   },
   { 
      "id":2,
      "name":"name2",
      "color":[ 
         "pink",
         "yellow"
      ]
   }
]

Expected Output:

["name1", "name2"]

Show Solution
import json

sampleJson = """[ 
   { 
      "id":1,
      "name":"name1",
      "color":[ 
         "red",
         "green"
      ]
   },
   { 
      "id":2,
      "name":"name2",
      "color":[ 
         "pink",
         "yellow"
      ]
   }
]"""

data = []
try:
    data = json.loads(sampleJson)
except Exception as e:
    print(e)

dataList = [item.get('name') for item in data]
print(dataList)
Code language: Python (python)

Filed Under: Python, Python Exercises, Python JSON

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises Python JSON

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Comments

  1. Imagesahil butt says

    November 10, 2025 at 8:34 pm

    This website is very good, and helped me very much with the understanding os json. Especially opgave 9.

    Reply
  2. ImageMehdi says

    December 29, 2023 at 9:54 pm

    Hello
    I am very happy that I came across this interesting and useful website. It has very good exercises and I hope that this website will improve day by day and provide us with more exercises.
    For the last exercise, since I was not yet familiar with the try expect method, that’s why I wrote another answer model for this exercise, I will share it with you.

    import json
    json_data = “””[
    {
    “id”:1,
    “name”:”name1″,
    “color”:[
    “red”,
    “green”
    ]
    },
    {
    “id”:2,
    “name”:”name2″,
    “color”:[
    “pink”,
    “yellow”
    ]
    }
    ]”””
    json_data_list = json.loads(json_data)
    json_data_list_name = []
    for item in json_data_list:
    for key, value in item.items():
    if key == “name”:
    json_data_list_name.append(value)
    json_data_list_name_string = json.dumps(json_data_list_name)
    print(json_data_list_name_string)

    Reply
    • ImageMohammad Yusuf says

      April 10, 2025 at 3:43 pm

      import json

      json_data = “””[
      {
      “id”:1,
      “name”:”name1″,
      “color”:[
      “red”,
      “green”
      ]
      },
      {
      “id”:2,
      “name”:”name2″,
      “color”:[
      “pink”,
      “yellow”
      ]
      }
      ]”””

      json_data_list = json.loads(json_data)

      json_data_list_name = []
      for item in json_data_list:
      for key, value in item.items():
      if key == “name”:
      json_data_list_name.append(value)

      json_data_list_name_string = json.dumps(json_data_list_name)
      print(json_data_list_name_string)

      Reply
  3. Imagesreenu says

    October 25, 2021 at 11:39 am

    Very useful. Thanks
    I have a dataframe that is coming read_csv having date columns with different date formats (accepted and confirmed by business ) like below.

    the issue is we are getting dynamic format in columns. user entered/updated any accepted format in any column.
    Note: Column can have only one format

    accepted date formats – DD/MM/YY, mm-dd-yyyy and MMM-yy

    day1
    id,date1,date2,date3
    1,25/10/21,10-25-2021,Jun-21
    2,25/10/21,10-25-2021,Feb-20

    day2
    id,date1,date2,date3
    1,25/10/21,Jun-21,10-25-2021
    2,25/10/21,Feb-20,10-25-2021

    Now I want to create a function/method to convert all the above date to YYYY-MM-DD format. the rule is if any column has MMM-YY then it should be the last day of the month

    output

    day1
    id,date1,date2,date3
    1,2021-10-25,2021-10-25,2021-10-31

    day2
    id,date1,date2,date3
    1,2021-10-25,2021-10-31,2021-10-25
    2,2021-10-25,2020-02-29,202110-25

    Can you please help me? I have sent the mail last week. it would be a great help if you help me with this

    Reply
  4. ImageDebashis Das says

    September 28, 2021 at 11:19 am

    Exercise 6: Convert the following Vehicle Object into JSON

    
    import json
    
    class Vehicle:
        def __init__(self, name, engine, price):
            self.name = name
            self.engine = engine
            self.price = price
    
    vehicle = Vehicle("Toyota Rav4", "2.5L", 32000)
    
    # Convert it into JSON format

    This can be done also like this:

    
    di = vehicle.__dict__
    print(json.dumps(di, indent=4))
    Reply
  5. Imagerene salmon says

    August 8, 2021 at 2:47 am

    Just solved the last exercise very simply with pandas. check it out

    #Assign list to data
    
    data =[ 
       { 
          "id":1,
          "name":"name1",
          "color":[ 
             "red",
             "green"
          ]
       },
       { 
          "id":2,
          "name":"name2",
          "color":[ 
             "pink",
             "yellow"
          ]
       }
    ]

    #How to get expected output [‘name1’, ‘name2’]?

    [data[0]['name'],data[1]['name']]
    Reply
  6. Imagejia says

    October 22, 2020 at 2:51 pm

    Hi I have an issue with Question 8
    it shows an invalid syntax for “bonus”:800

    Reply
  7. ImageMunna says

    June 24, 2020 at 5:51 pm

    Hi Vishal,

    how to convert json data to CSV file

    Reply
    • ImageVishal says

      June 25, 2020 at 3:11 pm

      You can use pandas. so I will add one more article to cover this

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Exercises Python JSON
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement