Kufanya kazi na JSON katika Python: Geuza, Changanua, na Andika JSON

JSON(JavaScript Object Notation) ni umbizo maarufu la data linalotumika kubadilishana data kati ya programu. Python inasaidia upotoshaji wa JSON kupitia json moduli, hukuruhusu kubadilisha kati ya Python data na umbizo la JSON.

Hapa kuna hatua za kufanya kazi na JSON katika Python:

Badilisha Python data kuwa JSON

Tumia json.dumps(): Badilisha Python kitu(orodha, kamusi, nakala, n.k.) kuwa mfuatano wa JSON.

Tumia json.dump(): Andika Python data kwenye faili ya JSON.

 

Badilisha JSON kuwa Python data

Tumia json.loads(): Badilisha mfuatano wa JSON kuwa Python kitu(orodha, kamusi, nakala, n.k.).

Tumia json.load(): Soma data kutoka kwa faili ya JSON na uibadilishe kuwa Python data.

 

Mfano:

import json  
  
# Convert Python data to JSON  
data_dict = {"name": "John", "age": 30, "city": "New York"}  
json_string = json.dumps(data_dict)  
print(json_string)   # Output: {"name": "John", "age": 30, "city": "New York"}  
  
# Write Python data to a JSON file  
with open("data.json", "w") as f:  
    json.dump(data_dict, f)  
  
# Convert JSON to Python data  
json_data = '{"name": "John", "age": 30, "city": "New York"}'  
python_dict = json.loads(json_data)  
print(python_dict)   # Output: {'name': 'John', 'age': 30, 'city': 'New York'}  
  
# Read data from a JSON file and convert to Python data  
with open("data.json", "r") as f:  
    data_dict = json.load(f)  
    print(data_dict)   # Output: {'name': 'John', 'age': 30, 'city': 'New York'}  

Kumbuka kuwa unapotumia JSON, Python aina maalum za data kama None, True, False zitabadilishwa hadi uwakilishi wao sambamba wa JSON: null, true, false, mtawalia.