Python’s json module allows you to work with JSON (JavaScript Object Notation) files, which are widely used for data exchange.
Reading from a JSON File
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
json.load(file): Reads the JSON file and converts it into a Python dictionary or list.
Writing to a JSON File
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
json.dump(data, file): Writes the data as JSON.
indent=4: Makes the JSON output formatted for readability.
Converting Between JSON Strings and Python Dictionaries
From JSON string to dictionary: json.loads(json_string)
From dictionary to JSON string: json.dumps(dictionary)
# Convert JSON string to Python dictionary
json_string = '{"name": "John", "age": 35, "city": "London"}'
data = json.loads(json_string)
print(data)
# Convert Python dictionary to JSON string
dictionary = {"name": "Tom", "age": 30, "city": "New York"}
json_str = json.dumps(dictionary, indent=4)
print(json_str)
Python working with JSON files – Interview Questions
Q 1: How do you read JSON files in Python?
Ans: Using the json.load() method.
Q 2: How do you write JSON files?
Ans: Using the json.dump() method.
Q 3: What module is used for JSON in Python?
Ans: The built-in json module.
Q 4: Can Python dictionaries be converted to JSON?
Ans: Yes, using json.dumps().
Q 5: Can JSON support nested data structures?
Ans: Yes, JSON can store nested dictionaries and lists.
Python working with JSON files – Objective Questions (MCQs)
Q1. Which module is used to work with JSON in Python?
Q2. Which method converts a Python dictionary into a JSON string?
Q3. Which method reads a JSON object from a file?
Q4. Which method writes JSON data to a file?
Q5. What will json.loads('{"a":1}') return?