Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Read and Write JSON file in Python

To read and write JSON files in Python, you can use the built-in json module. This module provides two methods, json.dump() and json.load(), for writing and reading JSON data, respectively.

Here's an example of how to read and write JSON files in Python:

import json

# Data to be written to a JSON file
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Write JSON data to a file
with open("data.json", "w") as write_file:
    json.dump(data, write_file)

# Read JSON data from a file
with open("data.json", "r") as read_file:
    loaded_data = json.load(read_file)

print(loaded_data)

In this example, we first import the json module. We then create a Python dictionary called data, which contains some sample data.

To write the dictionary to a JSON file, we use the json.dump() method with a file object created using the open() function in write mode ("w"). This writes the JSON data to a file named "data.json".

To read the JSON data from the file, we use the json.load() method with a file object created using the open() function in read mode ("r"). The JSON data is loaded into a Python dictionary called loaded_data.

Finally, we print the loaded_data dictionary, which should be the same as the original data dictionary.

Note that you can also use json.dumps() and json.loads() to convert between Python objects and JSON strings, rather than working directly with files.

  1. How to use the json module in Python:

    • Description: The json module in Python provides methods for working with JSON (JavaScript Object Notation) data, allowing you to encode and decode JSON strings.
    • Example Code:
      import json
      
      data = {'name': 'John', 'age': 30, 'city': 'New York'}
      json_str = json.dumps(data)
      print(json_str)
      
  2. Reading JSON data from a file in Python:

    • Description: You can read JSON data from a file using the json.load function.
    • Example Code:
      import json
      
      with open('data.json', 'r') as file:
          json_data = json.load(file)
          print(json_data)
      
  3. Writing JSON to a file in Python:

    • Description: Use the json.dump function to write JSON data to a file.
    • Example Code:
      import json
      
      data = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
      with open('output.json', 'w') as file:
          json.dump(data, file)
      
  4. Reading and writing nested JSON in Python:

    • Description: Handling JSON data with nested structures, such as dictionaries within dictionaries or lists.
    • Example Code:
      import json
      
      nested_data = {'person': {'name': 'Bob', 'address': {'city': 'London', 'postcode': 'SW1A 1AA'}}}
      
      # Writing nested JSON to a file
      with open('nested_data.json', 'w') as file:
          json.dump(nested_data, file)
      
      # Reading nested JSON from a file
      with open('nested_data.json', 'r') as file:
          loaded_data = json.load(file)
          print(loaded_data)
      
  5. Error handling with JSON file operations in Python:

    • Description: Handling potential errors that may occur during JSON file operations, such as file not found or invalid JSON format.
    • Example Code:
      import json
      
      try:
          with open('nonexistent_file.json', 'r') as file:
              json_data = json.load(file)
              print(json_data)
      except FileNotFoundError:
          print("File not found.")
      except json.JSONDecodeError:
          print("Invalid JSON format.")
      
  6. Pretty print JSON in Python:

    • Description: Making JSON output more readable by formatting it with indentation.
    • Example Code:
      import json
      
      data = {'name': 'Eve', 'age': 28, 'city': 'Berlin'}
      json_str = json.dumps(data, indent=2)
      print(json_str)