A Python class that makes working with JSON files simpler. It provides an easy way to read, write, add to, and check JSON files, along with some extra helpful methods and features.
- Read JSON files with automatic file validation.
- Write JSON data as dictionaries or lists of dictionaries.
- Append data to existing JSON files.
- Clear JSON files.
- Validate JSON schema using the
jsonschemalibrary. - Access properties like
data(alias forread),keys,values,length,is_empty,size, andexists. - Pretty print data.
pip install json_file_helpergit clone https://github.com/TheBiemGamer/Json-File-Helper.git
cd json-helperInstall the requirements with pip or with poetry:
Pip:
pip install -r requirements.txtOr with Poetry:
poetry installfrom json_file_helper import json_filefrom json_file_helper import json_file
# Initialize with an optional file path
jf = json_file("example.json")data = jf.read()
print(data)Or with the data property:
data = jf.data
print(data)jf.write({"name": "John", "age": 30})Append a dictionary to a JSON dictionary or list:
jf.append({"city": "New York"})jf.clear()Use a JSON schema to validate the structure of your file:
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
}
is_valid = jf.validate_schema(schema)
print(f"Is valid: {is_valid}")jf.pretty_print()print(jf.keys) # List of keys in the JSON (if it's a dictionary)
print(jf.values) # List of values
print(jf.length) # Number of items (for dicts or lists)
print(jf.is_empty) # Check if the file is empty
print(jf.size) # File size in bytes
print(jf.exists) # Check if the file existsThe json_file class can also be used with with statements:
with json_file("example.json") as jf:
data = jf.read()
jf.append({"new_key": "new_value"})- Python 3.8+
jsonschemalibrary for schema validation
Here’s a complete example:
from json_file_helper import json_file
# Initialize with a file path
jf = json_file("example.json")
# Write data to the file
jf.write({"name": "Alice", "age": 25})
# Read the file
print(jf.data)
# Append new data
jf.append({"city": "London"})
# Validate schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age"]
}
print(jf.validate_schema(schema))
# Pretty print the file's content
jf.pretty_print()This project is licensed under the MIT License. See the LICENSE file for details.
TheBiemGamer (biemgamer@pm.me)