javascript-data-files
Work with JSON which is stored as a value in a JavaScript file
This is a collection of Python functions for manipulating JavaScript “data files” – that is, JavaScript files that define a single variable with a JSON value.
Think of this as the Python json module, but built specifically for JavaScript files like this:
const shape = { "sides": 5, "colour": "red" };Why not use JSON files?
If you open a local HTML file directly from your disk (file://...), browsers block you from loading local .json files via fetch() or XMLHttpRequest due to CORS (Cross-Origin Resource Sharing) restrictions.
However, you can load a local JavaScript file using a standard script tag:
<script src="file:///Users/alexwlchan/repos/javascript-data-files/data.js"></script>I build and maintain a lot of local static websites and offline HTML viewers. Storing my metadata in JavaScript files rather than JSON is the only way to load external data into these local files without the hassle of running a local web server.
I have a lot of local static websites that I use for my local media archives. Storing my metadata in JavaScript files rather than JSON allows me to load metadata in an HTML file without the hassle of running a local web server.
The minor annoyance of writing to .js files instead of pure .json is easily offset by the convenience of just double-clicking an HTML file to open it. This library bridges the gap, letting my Python backend scripts easily read, write, and update those JavaScript data files.
Usage
from javascript_data_files import (
read_js,
write_js,
append_to_js_array,
append_to_js_object,
read_typed_js,
)The library provides four core functions:
- Read: Get a file’s value with
read_js(path, varname) - Write: Create or overwrite a file with
write_js(path, value, varname) - Append to array: Add an item to a JavaScript array with
append_to_js_array(path, value) - Append to object: Add a key-value pair to a JavaScript object with
append_to_js_object(path, key, value)
If you install the typed extra, you can validate your JavaScript data against a Python type or Pydantic model:
- Typed read:
read_typed_js(path, varname, model)
Installation
You have two options:
Copy the
src/javascriptdirectory and its tests directly into your project. Just keep a link back here!Install via pip:
$ pip install javascript-data-filesTo include type-checking capabilities:
$ pip install javascript-data-files[typed]
Versioning and stability
This library uses semantic versioning. Patch and minor versions will not contain breaking changes.
In practice, the library is unlikely to change much in future versions – it does one specific job, and it does it well.
Development and feedback
Want to contribute or tweak something? Check out CONTRIBUTING.md for local setup instructions.
License
This project is shared under the MIT license.