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

preview_player
Показать описание
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"}'
print(type(data))

# Reading JSON data from a file
import json
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.
# Print the JSON-formatted string
print(json_string)

# Writing JSON data to a file
import json
data = {"name": "Alice", "age": 30, "city": "New York"}
# Write the 'data' dictionary to the file in JSON format

# Accessing JSON data as a dictionary
import json
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"}
print(json_string)

# Working with JSON data from an API
import requests
import json

# The .json() method parses the JSON data and converts it to a Python list or dictionary
print(type(data))
print(data)

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

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

#python #pythonforbeginners #pythonprogramming
Рекомендации по теме