Python JSON Files
In this page:
import json
data = json.loads(json_string)
json_string = json.dumps(data)
json.dump(data, file)
data = json.load(file)
json Module
JSON (JavaScript Object Notation) एक lightweight, text-based data format है जो web पर structured data exchange करने का standard बन चुका है, और Python का built-in json module बिना किसी external dependency के इसे और native Python objects के बीच convert करता है।
उदाहरण: The json Module
import json
data = {"name": "Alex"}
print(json.dumps(data)) # converts the dict to a JSON string
JSON Files पढ़ना
json.load(file_object) किसी खुली file की JSON content पढ़ता है और उसे एक ही call में सीधे Python objects (dicts, lists, strings, numbers) में parse कर देता है -- यह json.loads() से अलग है, जो file की बजाय आपके पास पहले से memory में मौजूद JSON string को parse करता है।
उदाहरण: Reading JSON Files
import json
with open("data.json", "w") as f:
json.dump({"name": "Alex"}, f)
with open("data.json", "r") as f:
data = json.load(f) # parses JSON straight from the open file
print(data)
JSON Files लिखना
json.dump(data, file_object) किसी Python dict या list को serialize करता है और उसकी resulting JSON text सीधे किसी खुली file में लिख देता है -- अगर आप एक घनी single line की बजाय human-readable formatted output चाहते हैं तो indent=2 को extra argument के रूप में pass करें।
उदाहरण: Writing JSON Files
import json
data = {"name": "Alex", "age": 30}
with open("data.json", "w") as f:
json.dump(data, f, indent=2) # indent=2 makes the output human-readable
with open("data.json") as f:
print(f.read())
JSON Data Types Conversion
json module दोनों दिशाओं में types को अपने आप map करता है: Python का None JSON के null में बदलता है, True/False true/false में बदलते हैं, और dicts/lists JSON objects/arrays में map होते हैं -- पर sets या datetime objects जैसे Python-specific types डिफ़ॉल्ट रूप से JSON-serializable नहीं होते और उन्हें custom handling चाहिए।
उदाहरण: JSON Data Types Conversion
import json
data = {"active": True, "value": None, "items": [1, 2]}
text = json.dumps(data) # True -> true, None -> null, list -> array
print(text)
Custom JSON Object Hooks
json.load()/loads() का object_hook parameter आपको एक function देने देता है जो decode होते समय हर parsed JSON object पर चलता है, यही तरीका है जिससे आप parsing के दौरान plain dicts को custom Python objects में (जैसे {x:1,y:2} को Point instance में) अपने आप बदल सकते हैं।
उदाहरण: Custom JSON Object Hooks
import json
def as_point(d): # runs on every parsed JSON object
if "x" in d and "y" in d:
return (d["x"], d["y"])
return d
result = json.loads('{"x": 1, "y": 2}', object_hook=as_point)
print(result)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: