Python working with JSON files

Python’s json module allows you to work with JSON (JavaScript Object Notation) files, which are widely used for data exchange.

Reading from a JSON File


import json

with open("data.json", "r") as file:
    data = json.load(file)
    print(data)

json.load(file): Reads the JSON file and converts it into a Python dictionary or list.

Writing to a JSON File


import json

data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

json.dump(data, file): Writes the data as JSON.

indent=4: Makes the JSON output formatted for readability.

Converting Between JSON Strings and Python Dictionaries

From JSON string to dictionary: json.loads(json_string)

From dictionary to JSON string: json.dumps(dictionary)


# Convert JSON string to Python dictionary
json_string = '{"name": "John", "age": 35, "city": "London"}'
data = json.loads(json_string)
print(data)

# Convert Python dictionary to JSON string
dictionary = {"name": "Tom", "age": 30, "city": "New York"}
json_str = json.dumps(dictionary, indent=4)
print(json_str)