ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 8 · 4లో పాఠం 1కోర్సులో 29/36~10 min
మాడ్యూల్ పాఠాలు (1/4)

JSON: సీరియలైజ్ చేసి అన్వయించండి

JSON is the most widespread data exchange format. The json module in the standard library handles it natively.

From Python to JSON: dumps

json.dumps(object) serializes a Python object into a JSON string.

Python
import json

dati = {"nome": "Ada", "anni": 36, "skills": ["python", "matematica"]}
json.dumps(dati)
# '{"nome": "Ada", "anni": 36, "skills": ["python", "matematica"]}'

json.dumps(dati, indent=2, sort_keys=True)
# multi-line formatted string, keys sorted

From JSON to Python: loads

json.loads(string) parses a JSON string and returns Python objects.

Python
testo = '{"nome": "Ada", "anni": 36}'
d = json.loads(testo)
d["nome"]    # 'Ada'
type(d)      # <class 'dict'>

Type mapping

JSONPython
objectdict
arraylist
stringstr
numberint / float
trueTrue
falseFalse
nullNone

From file: dump / load

Python
with open("config.json", "w") as f:
    json.dump(dati, f, indent=2)

with open("config.json") as f:
    dati = json.load(f)

Without the trailing "s" they work on files (file-like), with the "s" on strings.

Non-serializable types: default

datetime, set, your custom classes are not serializable by default:

Python
import datetime, json
json.dumps({"ora": datetime.datetime.now()})
# TypeError: Object of type datetime is not JSON serializable

You can pass a default function that tells how to transform them:

Python
def converti(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    if isinstance(obj, set):
        return list(obj)
    raise TypeError(f"non serializzabile: {type(obj)}")

json.dumps({"ora": datetime.datetime.now()}, default=converti)

JSON and file operations

The standard library also provides json.dump() and json.load() (without the 's') to write and read JSON data directly to and from files, pairing naturally with context managers:

Python
with open("data.json", "w") as f:
    json.dump(data, f)

Try it

వ్యాయామం#python.m8.l1.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Given `data = {'nome': 'Ada', 'anni': 36}`, serialize it to JSON with indent=2 and assign to the variable `json_str`. Evaluate `json_str`.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

json.dumps(data, indent=2)

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#python.m8.l1.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Given the JSON string s = '[{"nome": "a", "v": 1}, {"nome": "b", "v": 2}]', parse it with json.loads into data and compute the sum of the 'v' values in total. Evaluate total.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

json.loads returns a list of dicts.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Additional challenge

వ్యాయామం#python.m8.l1.e3
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Given the JSON string `json_data = '{"name": "Alice", "age": 30}'`, decode it into a Python dictionary using `json.loads`. Extract the value associated with the `'name'` key and store it in `user_name`. Finally, evaluate `user_name`.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Use json.loads(json_data) to decode, then access via data['name'].

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది