Add utils.toJson(obj) function to convert an object to a JSON string (#998)

* Add `utils.toJson(obj)` function to convert an object to a JSON string

* Add test for utils.toJson()
This commit is contained in:
JonnyWong16 2022-08-27 00:13:41 -07:00 committed by GitHub
parent ef12e64a6f
commit e640f57319
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 0 deletions

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import base64
import functools
import json
import logging
import os
import re
@ -604,3 +605,17 @@ def iterXMLBFS(root, tag=None):
if tag is None or node.tag == tag:
yield node
queue.extend(list(node))
def toJson(obj, **kwargs):
""" Convert an object to a JSON string.
Parameters:
obj (object): The object to convert.
**kwargs (dict): Keyword arguments to pass to ``json.dumps()``.
"""
def serialize(obj):
if isinstance(obj, datetime):
return obj.isoformat()
return {k: v for k, v in obj.__dict__.items() if not k.startswith('_')}
return json.dumps(obj, default=serialize, **kwargs)

View file

@ -91,3 +91,7 @@ def test_utils_download(plex, episode):
def test_millisecondToHumanstr():
res = utils.millisecondToHumanstr(1000)
assert res == "00:00:01.0000"
def test_toJson(movie):
assert utils.toJson(movie)