Yin aiki tare da JSON a cikin Python: Maida, Fassara, da Rubuta JSON

JSON(JavaScript Object Notation) sanannen tsarin bayanai ne da ake amfani da shi don musayar bayanai tsakanin aikace-aikace. Python yana goyan bayan magudin JSON ta hanyar json tsarin, yana ba ku damar canzawa tsakanin Python bayanai da tsarin JSON.

Anan ga matakan aiki tare da JSON a cikin Python:

Maida Python bayanai zuwa JSON

Yi amfani json.dumps(): Canza Python abu(jeri, ƙamus, tuple, da sauransu) zuwa kirtani JSON.

Yi amfani json.dump(): Rubuta Python bayanai zuwa fayil JSON.

 

Maida JSON zuwa Python bayanai

Yi amfani json.loads(): Maida kirtan JSON zuwa Python abu(jeri, ƙamus, tuple, da sauransu).

Yi amfani json.load(): Karanta bayanai daga fayil JSON kuma canza shi zuwa Python bayanai.

 

Misali:

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'}  

Lura cewa lokacin amfani da JSON, Python nau'ikan bayanai na musamman kamar None, True, False za a canza su zuwa daidaitattun wakilcin JSON su: null, true, false, bi da bi.