Nggarap JSON ing Python: Ngonversi, Parse, lan Tulis JSON

JSON(JavaScript Object Notation) minangka format data populer sing digunakake kanggo ijol-ijolan data antarane aplikasi. Python ndhukung manipulasi JSON liwat json modul, ngijini sampeyan kanggo ngowahi antarane Python data lan format JSON.

Mangkene langkah-langkah kanggo nggarap JSON ing Python:

Ngonversi Python data menyang JSON

Gunakake json.dumps(): Ngonversi Python obyek(dhaftar, kamus, tuple, lsp) menyang string JSON.

Gunakake json.dump(): Tulis Python data menyang file JSON.

 

Ngonversi JSON menyang Python data

Gunakake json.loads(): Ngonversi string JSON menyang Python obyek(dhaftar, kamus, tuple, lsp.).

Gunakake json.load(): Waca data saka file JSON lan konversi dadi Python data.

 

Tuladha:

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

Elinga yen nalika nggunakake JSON, Python jinis data khusus kaya None, True, False bakal diowahi dadi perwakilan JSON sing cocog: null, true, false, mungguh.