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

Source: https://ravindrabagale.com/mr/datascience/py09-how-to-read-and-write-csv-json-and-text-files-in-python/p9-5-how-to-read-and-write-json-files-in-python.html
Language: mr (Marathi with English technical terms)

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

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

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

Input file orders.json:

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

```python
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:

```text
Madrid Central
M1 35.5
M2 12.0
```

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

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

```python
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:

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

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

रवींद्र बागले यांची tip

API nested JSON देत असेल तर आधी एक record `print(json.dumps(rec, indent=2))` ने बघा. मग कोणते fields लागतात ते ठरवा.
