Skip to content

Instantly share code, notes, and snippets.

@xiaoruoruo
Last active December 28, 2024 16:14
Show Gist options
  • Save xiaoruoruo/3fdf8d0f92b3fd85f259b35f888e4257 to your computer and use it in GitHub Desktop.
Save xiaoruoruo/3fdf8d0f92b3fd85f259b35f888e4257 to your computer and use it in GitHub Desktop.
Convert beancount journal to a JSON format
#!/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)
@eklenin
Copy link

eklenin commented Jun 10, 2024

Adjustment for tags (Type not serializable <class 'frozenset'>: frozenset({'test-tag'})):

def json_serial(obj):
    print(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)}
    if isinstance(obj, frozenset): # <--
        return list(obj)
    raise TypeError("Type not serializable %s: %s" % (type(obj), obj))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment