Last active
December 28, 2024 16:14
-
-
Save xiaoruoruo/3fdf8d0f92b3fd85f259b35f888e4257 to your computer and use it in GitHub Desktop.
Convert beancount journal to a JSON format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from beancount import loader | |
from beancount.core.amount import Amount | |
from beancount.core.number import Decimal | |
from datetime import date | |
import json | |
import sys | |
def json_serial(obj): | |
if isinstance(obj, date): | |
serial = obj.isoformat() | |
return serial | |
if isinstance(obj, Decimal): | |
return float(obj) | |
if isinstance(obj, Amount): | |
return {obj.currency: float(obj.number)} | |
raise TypeError("Type not serializable %s: %s" % (type(obj), obj)) | |
def convert_entry(e): | |
name = type(e).__name__ | |
e = e._asdict() | |
e['_type'] = name | |
if 'postings' in e: | |
e['postings'] = [convert_entry(p) for p in e['postings']] | |
if e.get('meta', None) is not None and 'filename' in e['meta']: | |
del e['meta']['filename'] | |
return e | |
if __name__ == '__main__': | |
entries, errors, options = loader.load_file(sys.argv[1]) | |
result = json.dumps([convert_entry(e) for e in entries], default=json_serial) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adjustment for tags (
Type not serializable <class 'frozenset'>: frozenset({'test-tag'})
):