-
Hajipur, Bihar, 844101
JSON (JavaScript Object Notation) is a popular data format used for exchanging data between a client and server.
Python has a built-in package called json
to work with JSON data.
You must import the json
module before using it.
import json
Use json.dumps()
to convert Python objects into JSON strings.
import json
data = {"name": "Alice", "age": 25, "city": "Delhi"}
json_data = json.dumps(data)
print(json_data)
✅ Python dictionary is converted to a JSON string.
Use json.loads()
to convert a JSON string into a Python object.
import json
json_data = '{"name": "Alice", "age": 25, "city": "Delhi"}'
data = json.loads(json_data)
print(data["name"]) # Output: Alice
Use json.dump()
to write JSON data to a file.
with open("data.json", "w") as f:
json.dump(data, f)
Use json.load()
to read JSON data from a file.
with open("data.json", "r") as f:
content = json.load(f)
print(content)
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
Make JSON readable using indent
, sort_keys
, and separators
.
print(json.dumps(data, indent=4, sort_keys=True))
Q1. Write a Python program to convert a Python list to JSON using json.dumps()
.
Q2. Write a Python program to convert a JSON string to a dictionary using json.loads()
and access a specific value.
Q3. Write a Python program to write a Python dictionary to a .json
file using json.dump()
.
Q4. Write a Python program to read and print content from a .json
file using json.load()
.
Q5. Write a Python program to create a Python object with mixed data types (int, str, list, bool) and convert it to JSON.
Q6. Write a Python program to use sort_keys=True
in json.dumps()
and show sorted key output.
Q7. Write a Python program to add pretty formatting to JSON output using indent=2
in json.dumps()
.
Q8. Write a Python program to convert Python None
to JSON using json.dumps()
and verify the result (null
in JSON).
Q9. Write a Python program to store user information (like name, age) in a .json
file.
Q10. Write a Python program to read JSON content from a file and loop through all dictionary keys.
Q1: What does JSON stand for?
Q2: Which module is used for JSON in Python?
Q3: What does json.dumps() do?
Q4: What is the function to convert JSON string to Python object?
Q5: Which function writes JSON to a file?
Q6: Which data type in Python becomes null in JSON?
Q7: Which argument is used to pretty-print JSON?
Q8: What is the output of json.dumps(True)?
Q9: Which Python structure becomes a JSON array?
Q10: What does json.load() do?