Menu
Coddy logo textTech

json.loads()

Lesson 7 of 9 in Coddy's Python JSON course.

The json.loads() function is a crucial part of Python's json module. It's used to parse JSON strings and convert them into Python objects. This process is also known as deserialization.

Basic Usage

Here's the basic syntax of json.loads():


import json

python_object = json.loads(json_string)

The function takes a JSON-formatted string as input and returns a corresponding Python object.

Example

Let's parse a JSON string into a Python object:


import json

json_string = '{"name": "John", "age": 30, "city": "New York"}'

parsed_data = json.loads(json_string)
print(type(parsed_data))  # Output: <class 'dict'>
print(parsed_data)        # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

Data Type Conversion

json.loads() automatically converts JSON data types to their Python equivalents:

  • JSON objects become Python dictionaries
  • JSON arrays become Python lists
  • JSON strings become Python strings
  • JSON numbers become Python int or float
  • JSON true becomes Python True
  • JSON false becomes Python False
  • JSON null becomes Python None

This function is essential when you need to work with JSON data in Python, such as when receiving data from an API or reading from a JSON file.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a function that parses a JSON string containing information about a book and performs specific operations on the parsed data. The function should:

  1. Use json.loads() to parse the input JSON string.
  2. Extract the following information from the parsed data:
    • Title of the book
    • Number of pages
    • List of authors
  3. Perform the following operations:
    • Convert the title to uppercase
    • Increase the number of pages by 10
    • Sort the list of authors alphabetically
  4. Create a new dictionary with the modified data.
  5. Return a string in the format: "TITLE | Pages: X | Authors: A, B, C"

The following input will be provided:


{"title": "Python Programming", "pages": 300, "authors": ["John Smith", "Alice Johnson", "Bob Wilson"]}

Print the resulting string.

Try it yourself

import json

# Read input
json_string = input()

# TODO: Write your code below
def parse_and_modify_book_data(json_string):
    # Parse the JSON string
    
    # Extract required information
    
    # Modify the data
    
    # Create a new dictionary with modified data
    
    # Format the result string
    
    return result_string

# Call the function and print the result
print(parse_and_modify_book_data(json_string))

All lessons in Python JSON