
![]() |
@wtf | |
(Fetch weather data) |
||
1
Replies
6
Views
1 Bookmarks
|
![]() |
@wtf | 6 days |
*Working with JSON & APIs in Python* *What is JSON?* JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data between systems (especially in web APIs). It looks like this: name: Alice, age: 30, skills: [Python, SQL] Python treats JSON data like dictionaries and lists. *How to Handle JSON in Python* import json Convert Python dict to JSON string person = name: Alice, age: 30 json_string = json.dumps(person) print(json_string) Convert JSON string to Python dict data = 'name: Bob, age: 25' person_dict = json.loads(data) print(person_dict[name]) Output: Bob *What is an API?* An API (Application Programming Interface) allows different systems to talk to each other. You send a request → you get a response (usually in JSON). *Making a Simple API Call (using mock data)* import requests response = requests.get(https://jsonplaceholder.typicode.com/users/1) data = response.json() print(fName: data['name']) print(fEmail: data['email']) This fetches data from a public fake API and prints the name and email of a user. *Mini Project: Mock Weather App* import requests def get_weather(): city = input(Enter your city: ) print(fFetching weather for city...) Mock response structure weather_data = Delhi: temp: 32°C, condition: Sunny, Mumbai: temp: 28°C, condition: Rainy, if city in weather_data: info = weather_data[city] print(fTemperature: info['temp'], Condition: info['condition']) else: print(Sorry, no data available.) get_weather() *What You Practiced* : - JSON serialization/deserialization - Making HTTP requests using requests - Accessing and using API response data - Mocking real-world scenarios |
||


