Working with JSON in Python: Convert, Parse, and Write JSON

JSON (JavaScript Object Notation) is a popular data format used for data exchange between applications. Python supports JSON manipulation through the json module, allowing you to convert between Python data and JSON format.

Here are the steps for working with JSON in Python:

Convert Python data to JSON

Use json.dumps(): Convert a Python object (list, dictionary, tuple, etc.) to a JSON string.

Use json.dump(): Write Python data to a JSON file.

 

Convert JSON to Python data

Use json.loads(): Convert a JSON string to a Python object (list, dictionary, tuple, etc.).

Use json.load(): Read data from a JSON file and convert it to Python data.

 

Example:

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

Note that when using JSON, special Python data types like None, True, False will be converted to their corresponding JSON representations: null, true, false, respectively.