Back to all posts

Working with JSON Data in Python (Using APIs and Built-in JSON Module)

इस टॉपिक में हम Python में JSON (JavaScript Object Notation) के साथ कैसे काम करते हैं, ये सीखते हैं। JSON एक डेटा फॉर्मेट है जो डेटा को store और transfer क…

इस टॉपिक में हम Python में JSON (JavaScript Object Notation) के साथ कैसे काम करते हैं, ये सीखते हैं। JSON एक डेटा फॉर्मेट है जो डेटा को store और transfer करने के लिए इस्तेमाल होता है, खासकर APIs में।


🔹 Python में JSON के साथ काम करने के लिए json module का इस्तेमाल होता है।

✅ 1. JSON string को Python dictionary में बदलना (JSON ➡️ Python)

Python
import json

x = '{ "name":"John", "age":30, "city":"New York"}'
print(type(x))  # <class 'str'>

y = json.loads(x)  # JSON string to Python dict
print(type(y))     # <class 'dict'>
print(y)   # Output: John

🔸 json.loads() का मतलब है Load String — JSON string को Python dictionary में बदलना।


✅ 2. Python dictionary को JSON string में बदलना (Python ➡️ JSON)

Bash
x = {'name': 'John', 'age': 30, 'city': 'New York'}
print(type(x))  # <class 'dict'>

y = json.dumps(x)
print(type(y))  # <class 'str'>

🔸 json.dumps() का मतलब है Dump String — Python dictionary को JSON format में बदलना (string के रूप में)।


⚠️ Common Mistake:

Python
x =  '{ "name":"John", "age":30, "city":"New York"}'
x = x.replace("'", "")  # ऐसा करने से JSON format corrupt हो सकता है
print(x)
print(type(x))
# print(x)  # ❌ Error: string indices must be integers

यहाँ, x एक string है, इसलिए x पर error आएगा। पहले json.loads(x) करके dictionary में बदलना होगा।


✅ JSON को सुंदर (pretty) प्रिंट करना:

Python
x = { "name":"John", "age":30, "city":"New York"}
x = json.dumps(x, indent=4, sort_keys=True)
print(x)

🔹 indent=4 ➡️ चार spaces का indentation देता है
🔹 sort_keys=True ➡️ keys को alphabetically sort करता है


🎯 Summary (सारांश):

JSON Functionकाम
json.loads()JSON string को Python object (dict) में बदले
json.dumps()Python object को JSON string में बदले
indentJSON को readable बनाए
sort_keysKeys को sort करके प्रिंट करे

Python
import json
import urllib.request

# Step 1: API URL (demo purpose)
url = "https://api.open-meteo.com/v1/forecast?latitude=40.71&longitude=-74.01&current_weather=true"

# Step 2: URL से डेटा पढ़ना
response = urllib.request.urlopen(url)
data = response.read()

# Step 3: JSON को Python dictionary में बदलना
weather_data = json.loads(data)

# Step 4: डेटा उपयोग करना
print("City: New York")
print("Temperature:", weather_data, "°C")
print("Wind Speed:", weather_data, "km/h")

ध्यान दें:

  • API से जो डेटा आता है, वो हमेशा JSON format में string होता है।
  • पहले उसे json.loads() से dictionary में बदलते हैं।
  • फिर dictionary से keys जैसे "temp", "humidity", "weather" आदि को access करते हैं।

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.