JSON মডিউল
পাইথনের json মডিউল স্ট্যান্ডার্ড লাইব্রেরিতে আছে। ইমপোর্ট: import json
পাইথন অবজেক্ট → JSON স্ট্রিং (Serialization)
| মেথড | বিবরণ |
json.dumps(obj) | অবজেক্টকে JSON স্ট্রিংতে কনভার্ট |
json.dump(obj, file) | অবজেক্টকে ফাইলে JSON হিসেবে লেখা |
উদাহরণ
import json
from io import StringIO
# ডিক্ট -> JSON স্ট্রিং
data = {"name": "Kalyan", "age": 25, "city": "Delhi"}
json_str = json.dumps(data, indent=4, ensure_ascii=False)
print(json_str)
# {
# "name": "Kalyan",
# "age": 25,
# "city": "Delhi"
# }
# ফাইলে লিখা
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
# StringIO-তে (মেমরি-তে)
sio = StringIO()
json.dump(["India", "Australia", "Brazil"], sio)
print(sio.getvalue()) # ["India", "Australia", "Brazil"]
JSON স্ট্রিং → পাইথন অবজেক্ট (Deserialization)
| মেথড | বিবরণ |
json.loads(str) | JSON স্ট্রিং থেকে পাইথন অবজেক্ট |
json.load(file) | ফাইল থেকে পাইথন অবজেক্ট |
উদাহরণ
import json
from io import StringIO
# স্ট্রিং থেকে
s = '["xyz", "abc", "pqr"]'
print(json.loads(s)) # ['xyz', 'abc', 'pqr']
# ডুপ্লিকেট কী হলে শেষটাই থাকে
s2 = '{"Asim": 25, "Priyesh": 23, "Asim": "28"}'
print(json.loads(s2)) # {'Asim': '28', 'Priyesh': 23}
# StringIO থেকে
sio = StringIO('["xyz", "abc", "pqr"]')
print(json.load(sio)) # ['xyz', 'abc', 'pqr']
কাস্টম JSON Encoder (কমপ্লেক্স অবজেক্ট হ্যান্ডলিং)
import json
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, complex):
return {"__complex__": True, "real": obj.real, "imag": obj.imag}
return super().default(obj)
# ব্যবহার
c = 5 + 8j
json_str = json.dumps(c, cls=ComplexEncoder)
print(json_str) # {"__complex__": true, "real": 5.0, "imag": 8.0}
# ডিকোডার দিয়ে ফিরে আনা
def as_complex(dct):
if "__complex__" in dct:
return complex(dct["real"], dct["imag"])
return dct
obj = json.loads(json_str, object_hook=as_complex)
print(obj) # (5+8j)
print(type(obj)) #
JSONDecoder কাস্টমাইজেশন
import json
decoder = json.JSONDecoder()
s = '{"Asim": 25, "Priyesh": 23}'
# parse
result = decoder.decode(s)
print(result) # {'Asim': 25, 'Priyesh': 23}
# raw_decode: স্ট্রিংয়ের শুরু থেকে পার্স করে (বাকি স্ট্রিং রিটার্ন করে)
result, idx = decoder.raw_decode(s + ' extra')
print(result) # {'Asim': 25, 'Priyesh': 23}
print(idx) # 38 (পার্স হওয়া দৈর্ঘ্য)
সাধারণ প্যারামিটারস
indent — প্রিটি-প্রিন্টের জন্য ইন্ডেন্টেশন (ইন্ট বা স্ট্রিং)
ensure_ascii — True হলে non-ASCII ক্যারেক্টার এস্কেপ হয় (ডিফল্ট True)
sort_keys — কীগুলো সর্ট করে (ডিফল্ট False)
separators — কম্প্যাক্ট আউটপুটের জন্য (',', ':')
default — সিরিয়ালাইজ না হওয়া অবজেক্টের জন্য ফাংশন
object_hook — ডিক্ট ডিকোডের পর কলব্যাক
object_pairs_hook — অর্ডারড ডিক্টের জন্য (pairs লিস্ট পায়)