{TypeError} Object of type Commit is not JSON serializable

Question:

I’ve a dict with some repo information and I want to write it a json file, but this error raises during dumps method: {TypeError} Object of type Commit is not JSON serializable.

__repo_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))

repo = Repo(__repo_path)

__tags = sorted(
      (tag for tag in repo.tags if tag.commit.committed_datetime <= repo.head.commit.committed_datetime),
            key=lambda t: t.commit.committed_datetime,)

try:
    __current_branch = repo.active_branch
except TypeError as e:
    __current_branch = "release"

SCM_DATA = {
            "CHANGESET": repo.head.commit,
            "BRANCH": __current_branch,
            "TAG": __tags[-1],
            "IS_DIRTY": repo.is_dirty(),
        }

json_version = json.dumps(SCM_DATA)

How can I fix it?

Asked By: Gimbo

||

Answers:

Make sure to use names/text messages not objects:

import git, json

repo = git.Repo('C:/data/foo')
__current_branch = repo.active_branch.name
__tags = repo.tags

SCM_DATA = {
    "CHANGESET": repo.head.commit.message,
    "BRANCH": __current_branch,
    "TAG": __tags[-1].name,
    "IS_DIRTY": repo.is_dirty(),
}

json_version = json.dumps(SCM_DATA)
print(json_version)

Out:

{'CHANGESET': 'inital commit', 'BRANCH': 'dev', 'TAG': 'v0.0.1', 'IS_DIRTY': True}
Answered By: MafMal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.