Python Tutorial: The json module for beginners // network engineers

Опубликовано: 27 Март 2025
на канале: Ferds Tech Channel
150
3

In this video, I will talk about the json module in python which is part of the python standard librabry.

What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read
and write, and easy for machines to parse and generate.

Why use JSON in Python?
JSON is commonly used for data interchange between a server and a client, especially with web APIs.

.loads() - Deserialize (Decode): Converting a JSON string into a Python object.
.dumps() - Serialize (Encode): Converting a Python object into a JSON string.


Importing json module
import json

Reading JSON data from a string
import json
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
data = json.loads(json_string) # Parse the JSON string into a Python dictionary
print(type(data))

Reading JSON data from a file
import json
with open('data.json', 'r') as file:
data = json.load(file) # The json.load() function converts the JSON data into a Python object
print(data)
print(type(data))

Writing JSON data to a string
import json
Define JSON data as a Python dictionary
data = {"name": "Alice", "age": 30, "city": "New York", "female": True}
Convert the Python dictionary into a JSON-formatted string.
json_string = json.dumps(data)
Print the JSON-formatted string
print(json_string)

Writing JSON data to a file
import json
data = {"name": "Alice", "age": 30, "city": "New York"}
with open('data.json', 'w') as file:
Write the 'data' dictionary to the file in JSON format
The json.dump() function converts the dictionary to JSON and writes it to the file
json.dump(data, file)

Accessing JSON data as a dictionary
import json
data = json.loads('{"name": "Alice", "age": 30, "city": "New York"}')
print(data['name']) # Output: Alice
print(data['age']) # Output: 30
print(data['city']) # Output: New York

Modifying JSON data
data['age'] = 31
print(data) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}

Pretty-printing JSON data
import json
data = {"name": "Alice", "age": 30, "city": "New York"}
json_string = json.dumps(data, indent=2)
print(json_string)

Working with JSON data from an API
import requests
import json

response = requests.get('https://jsonplaceholder.typicode.com/...)
The .json() method parses the JSON data and converts it to a Python list or dictionary
data = response.json()
print(type(data))
print(data)

Fetching and processing JSON data from a public API
import requests
import json

response = requests.get('https://jsonplaceholder.typicode.com/...)
data = response.json()

for user in data:
print(f"Name: {user['name']}, Email: {user['email']}, City: {user['address']['city']}")

#python #pythonforbeginners #pythonprogramming