Explore programming tutorials, exercises, quizzes, and solutions!
Python Working with JSON Exercises
1/15
JSON (JavaScript Object Notation) is a lightweight, widely used format for storing and exchanging structured data between applications. In Python, the built-in json module makes it easy to parse (load) JSON strings into Python objects and convert (dump) Python objects into JSON strings.
JSON is commonly used in web development, APIs, configuration files, and data interchange between systems. Understanding how to handle JSON in Python is crucial when building real-world applications.
Consider the following Python code:
import json
data = '{"name": "Alice", "age": 30, "city": "New York"}'
parsed = json.loads(data)
print(parsed["name"])
What does this code demonstrate about Python’s handling of JSON?
This code snippet uses the json.loads() function to parse a JSON-formatted string into a Python dictionary.
data is a valid JSON string that contains key-value pairs.
json.loads(data) converts the string into a Python dictionary:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
You can then access values using dictionary syntax like parsed["name"].
The json module also includes:
json.dumps() to convert Python objects (like dicts or lists) into JSON strings.
json.load() and json.dump() to read from and write to files.
This is useful when working with web APIs, config files, and data exchange formats — making JSON an essential skill in every Python developer’s toolkit.
How can you convert a Python dictionary into a JSON string?
The correct method to convert a Python dictionary into a JSON string is json.dumps(). The dumps method stands for "dump string," and it serializes a Python object into a JSON-formatted string. The other options are either incorrect method names or functions that don't exist in the json module.
Which of the following is the correct way to load a JSON string into a Python dictionary?
The correct method to load a JSON string into a Python dictionary is json.loads(), where loads stands for "load string." This method parses the JSON string and returns a Python dictionary. The other options use incorrect methods or function names.
When using json.dumps(), the Python dictionary is serialized into a JSON-formatted string. The correct format for JSON keys and string values includes double quotes, so the output will be {"name": "Alice", "age": 25}. Option 3 uses single quotes, which is not valid for JSON, and option 4 uses square brackets, which represent lists in JSON.
Which method in the json module is used to write JSON data to a file?
The correct method to write JSON data to a file is json.dump(). This method serializes a Python object and writes it to a file in JSON format. The other options are not valid methods in the json module.
You have a JSON file data.json containing the following data:
Which of the following code snippets correctly loads the file and retrieves the names of all students?
In this question, we need to load the contents of the data.json file into a Python object using json.load(f) and then access the list of students to extract their names. Option 1 is the correct one because it uses the json.load() function to parse the file, and the list comprehension correctly accesses the "students" key to retrieve each student's name. The other options either use incorrect methods or try to access the file object instead of the data.
You need to increase the price of all products by 10%. Which code snippet will correctly perform this task?
To increase the price of all products by 10%, the correct approach is to load the JSON data using json.load(f), iterate through the list of products, and multiply each product's price by 1.10 to get a 10% increase. Option 1 is correct because it uses json.load() to parse the file and correctly updates the prices. The other options either use incorrect methods (json.loads() for file input or json.dumps() for dumping) or incorrectly update the price.
You have a JSON object that contains nested data, and you want to extract a specific field from it. Given the following JSON data:
Which of the following code snippets correctly extracts the "city" value?
In this case, the correct way to access the "city" value is by navigating through the nested structure: data["user"]["address"]["city"]. Option 1 correctly accesses the "user" dictionary, then the "address" dictionary, and finally the "city" key. The other options either omit the "address" key or attempt to access "city" incorrectly.
What will be the result of the following code snippet?
In the code, the json.loads() method is used to parse the JSON string into a Python dictionary. The value of "age" is then updated to 35. The dictionary is then converted back into a JSON string using json.dumps(), and the output will reflect the updated "age" value. Therefore, the correct output is {"name": "John", "age": 35}.
Given the following JSON data, you want to retrieve all names of employees who have an age greater than 30. How would you accomplish this?
The correct approach is to load the JSON data using json.load(f) and then filter the employees whose age is greater than 30 using a list comprehension. Option 1 correctly implements this logic by checking emp["age"] > 30. Option 2 and Option 3 are incorrect because they either filter by age less than or equal to 30 or exactly equal to 30, which doesn’t match the requirement. Option 4 retrieves all employee names, regardless of age.
You have a nested JSON object with user data. You want to calculate the average age of all users whose "status" is "active". Given the following JSON data:
Which of the following code snippets will correctly compute the average age of all active users?
To calculate the average age of active users, we first filter out users with the "status" of "active". Then we compute the sum of their ages and divide it by the number of active users to get the average. Option 1 correctly implements this approach. Option 2 omits dividing by the number of users, and Option 3 incorrectly attempts to divide the list by its length. Option 4 filters inactive users, which is not the correct condition.
You have a large JSON object containing data about various products, and you need to sort the products by their price in descending order. Given the following JSON data:
Which of the following code snippets will correctly sort the products by price in descending order?
To sort the products by price in descending order, we use sorted() with the key argument set to a lambda function that accesses the "price" key, and reverse=True to ensure descending order. Option 4 is correct. Option 1 sorts in ascending order (reverse=False), while Option 2 sorts in ascending order without specifying the reverse flag. Option 3 incorrectly sorts by product name instead of price.
You have a JSON file containing employee data, and you need to update the salary of all employees by adding a 5% bonus. Given the following JSON data:
Which of the following code snippets will correctly add a 5% bonus to all employee salaries?
To add a 5% bonus, the salary should be increased by multiplying the current salary by 0.05 and adding that to the original salary. Option 3 correctly implements this approach. Option 1 is incorrect because it multiplies the salary by 1.05 directly, which would still work but is less clear. Option 2 adds a fixed value 0.05 rather than a percentage, which is incorrect. Option 4 adds a fixed bonus of 5, which doesn’t account for percentages.
You have the following JSON object with transaction data. You need to calculate the total amount of transactions for each user, where the transaction type is "credit". Given the following JSON data:
Which of the following code snippets will correctly calculate the total amount for each user where the transaction type is "credit"?
Option 3 correctly calculates the total credit amount per user by using totals.get(transaction["user_id"], 0) to ensure that if the user does not yet exist in the dictionary, their initial amount is set to 0 before adding the transaction amount. Option 1 correctly calculates the total but uses a manual check for existing users, while Option 2 incorrectly filters by "debit" transactions. Option 4 only stores the last "credit" transaction amount for each user, rather than summing them.
You are given a JSON file containing information about a series of orders. Each order contains product details and their respective prices. You need to calculate the total cost of each order, including tax, where the tax rate is 10%. Given the following JSON data:
Which of the following code snippets will correctly calculate the total cost for each order, including a 10% tax?
In Option 2, the code correctly calculates the total cost of all products in an order using sum(), then applies a 10% tax (total_cost * 0.10) and adds it to the original total. Option 1 uses an incorrect tax rate of 5%. Option 3 incorrectly divides by (1 - tax_rate) instead of multiplying by (1 + tax_rate) to calculate the tax. Option 4 calculates only the tax, not the total cost with tax.
Practicing Python Working with JSON? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Working with JSON
Welcome to the Python Working with JSON exercises — a practical set of challenges designed to help you master handling JSON data in Python. JSON (JavaScript Object Notation) is a widely-used data format for exchanging information between web servers, applications, and APIs. Whether you’re working on web development, data analysis, or integrating third-party services, understanding how to parse, manipulate, and generate JSON is an essential skill for Python programmers.
In this section, you’ll learn how to use Python’s built-in json module to encode Python objects into JSON strings and decode JSON data back into Python dictionaries and lists. These exercises will guide you through parsing complex JSON structures, handling nested data, and converting Python objects into JSON format suitable for storage or transmission.
You will practice reading JSON from files and APIs, modifying JSON content programmatically, and writing JSON back to files. Understanding how to navigate JSON data effectively enables you to work seamlessly with RESTful APIs, configuration files, and data interchange formats used in many modern applications.
Working with JSON in Python is particularly important for developers dealing with web services, IoT devices, or cloud-based platforms where JSON is the standard format for data communication. These exercises also prepare you for technical interviews that commonly include questions on data serialization and parsing.
Along with practical coding challenges, this section emphasizes best practices such as validating JSON data before processing, handling errors gracefully, and using Python’s advanced features to pretty-print or customize JSON output. These techniques improve your code’s robustness and readability.
We recommend supplementing your learning with related topics such as file handling, dictionaries, and APIs to develop a well-rounded skill set for data-driven Python programming. Quizzes and multiple-choice questions on JSON handling are also available to reinforce your knowledge.
Start practicing the Python Working with JSON exercises today to become proficient in managing JSON data effectively. With regular practice, you’ll confidently work with JSON in any Python project, making your applications more versatile and connected.