Parsing JSON Strings β json.loads()
json.loads() converts a JSON string into Python objects.
Python
import json
json_string = '''{
"name": "Alice",
"age": 30,
"skills": ["Python", "SQL"],
"active": true
}'''
data = json.loads(json_string)
print(data["name"]) # Alice
print(data["age"]) # 30
print(data["skills"]) # ['Python', 'SQL']
print(type(data)) # βΆ Output
Alice
30
['Python', 'SQL']
Converting to JSON String β json.dumps()
json.dumps() converts Python objects to a JSON string.
Python
import json
python_dict = {
"name": "Bob",
"scores": [95, 87, 92],
"passed": True,
"grade": None
}
# Basic conversion
json_str = json.dumps(python_dict)
print(json_str)
# Pretty-printed with indentation
pretty = json.dumps(python_dict, indent=2)
print(pretty)βΆ Output
{"name": "Bob", "scores": [95, 87, 92], "passed": true, "grade": null}
{
"name": "Bob",
"scores": [95, 87, 92],
"passed": true,
"grade": null
}Reading and Writing JSON Files
Use json.load() and json.dump() for file operations.
Python
import json
# Write JSON to file
data = {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON from file
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["users"][0]["name"]) # AliceAd β 336Γ280
Real-World: Processing API Responses
Most web APIs return JSON. Here is the standard pattern for consuming one.
Python
import json
import urllib.request
# Fetch from a public API
url = "https://api.github.com/users/python"
with urllib.request.urlopen(url) as response:
data = json.loads(response.read())
print(data["name"]) # Python
print(data["public_repos"]) # number of repos
print(data["followers"]) # follower countPython β JSON Type Mapping
JSON has a limited set of types. Python converts automatically.
Python
# Python β JSON type mapping:
# dict β object {}
# list β array []
# str β string ""
# int/floatβ number 42, 3.14
# True β true
# False β false
# None β null
# Verify:
print(json.dumps({"a": True, "b": None, "c": [1,2]}))βΆ Output
{"a": true, "b": null, "c": [1, 2]}