Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P9.5 Python मध्ये JSON Files कशा वाचायच्या आणि लिहायच्या?

By Ravindra Bagale

हे का शिकायचं?

APIs आणि settings JSON मध्ये असतात. तो Python च्या dict/list सारखाच दिसतो.

हे काय आहे?

json.load(f) file वाचून dict/list देतो. json.dump(data, f, indent=2, ensure_ascii=False) छान format मध्ये लिहितो; ensure_ascii=False ने ₹ आणि मराठी अक्षरं तशीच राहतात.

कसं करायचं?

Step 1. import json

Step 2. वाचायला json.load

Step 3. लिहायला json.dump

उदाहरणं: copy करा आणि चालवा

उदाहरण A: JSON file वाचा

आधी त्याच folder मध्ये orders.json ही input file तयार करा:

{"shop": "Madrid Central", "currency": "EUR", "orders": [{"id": "M1", "total": 35.5}, {"id": "M2", "total": 12.0}]}

हा code चालवा:

import json
with open("orders.json", encoding="utf-8") as f:
    data = json.load(f)
print(data["shop"])
for o in data["orders"]:
    print(o["id"], o["total"])

तुम्हाला दिसणारा output:

Madrid Central
M1 35.5
M2 12.0

याचा अर्थ: JSON चं Python dictionary झालं.

उदाहरण B: JSON लिहा

हा code चालवा:

import json
settings = {"region": "EU", "currency": "€", "top_n": 5}
with open("settings.json", "w", encoding="utf-8") as f:
    json.dump(settings, f, indent=2, ensure_ascii=False)
print(open("settings.json", encoding="utf-8").read())

तुम्हाला दिसणारा output:

{
  "region": "EU",
  "currency": "€",
  "top_n": 5
}

याचा अर्थ: indent=2 ने file वाचायला सोपी झाली.