{"id":7324,"library":"json-encoder","title":"JSON Encoder","description":"json-encoder is a Python library (version 0.4.4) designed to simplify JSON serialization by using the `singledispatch` pattern, eliminating the need for extensive `json.dumps(data, cls=MyJSONEncoder)` calls. It offers default serialization for common types like `time`, `date`, `datetime`, `UUID`, and `Decimal`, and can parse JSON float numbers into `Decimal` objects to mitigate Python float precision issues. The library is designed to be largely independent of specific underlying JSON implementations (e.g., `json`, `simplejson`, `ujson`), allowing users to choose their preferred backend.","status":"maintenance","version":"0.4.4","language":"en","source_language":"en","source_url":"https://github.com/hbasria/json-encoder","tags":["json","encoding","serialization","singledispatch","decimal","datetime","uuid"],"install":[{"cmd":"pip install json-encoder","lang":"bash","label":"Install latest version"}],"dependencies":[],"imports":[{"note":"Provides the primary `dumps` and `loads` functions, enhanced with singledispatch.","symbol":"json","correct":"from json_encoder import json"},{"note":"Used to globally configure the underlying JSON library (e.g., simplejson, ujson).","symbol":"use_json_library","correct":"from json_encoder import use_json_library"},{"note":"Decorator for registering custom serialization functions for specific types.","symbol":"json_encoder.register","correct":"from json_encoder.encoder import json_encoder\n@json_encoder.register(MyCustomType)"}],"quickstart":{"code":"from datetime import datetime, date\nfrom decimal import Decimal\nfrom fractions import Fraction\nfrom uuid import UUID\n\nfrom json_encoder import json\nfrom json_encoder import use_json_library\nfrom json_encoder.encoder import json_encoder\n\n# Optionally configure a specific JSON backend (e.g., ujson if installed)\ntry:\n    import ujson\n    use_json_library(ujson)\n    print(\"Using ujson backend\")\nexcept ImportError:\n    print(\"ujson not found, using default json backend\")\n\n# 1. Basic usage with built-in enhanced types\ndata = {\n    'now': datetime.now(),\n    'today': date.today(),\n    'money': Decimal('123.45'),\n    'id': UUID('12345678-1234-5678-1234-567812345678'),\n    'value': 1.23 # will be handled as Decimal due to float parsing\n}\n\nencoded_data = json.dumps(data, indent=2)\nprint(\"\\nEncoded data with default handlers:\")\nprint(encoded_data)\n\n# 2. Registering a custom type handler using singledispatch\nclass MyCustomType:\n    def __init__(self, name, value):\n        self.name = name\n        self.value = value\n\n@json_encoder.register(MyCustomType)\ndef encode_my_custom_type(obj: MyCustomType):\n    return {\n        'custom_name': obj.name,\n        'custom_value': obj.value,\n        'type_info': 'MyCustomType serialized'\n    }\n\ncustom_data = {'item': MyCustomType('test', 100)}\nencoded_custom_data = json.dumps(custom_data, indent=2)\nprint(\"\\nEncoded data with custom type handler:\")\nprint(encoded_custom_data)\n\n# 3. Example for Fraction (from PyPI docs)\n@json_encoder.register(Fraction)\ndef encode_fraction(obj: Fraction):\n    return float(obj)\n\nfraction_data = {'ratio': Fraction(1, 3)}\nencoded_fraction = json.dumps(fraction_data, indent=2)\nprint(\"\\nEncoded Fraction:\")\nprint(encoded_fraction)\n","lang":"python","description":"This quickstart demonstrates how to use `json-encoder` for basic data types that are typically not JSON-serializable (like `datetime`, `Decimal`, `UUID`), and how to register a custom serialization function for your own classes using the `singledispatch` decorator. It also shows how to optionally switch the underlying JSON library."},"warnings":[{"fix":"Use the `@json_encoder.register(Type)` decorator to define custom serialization logic for specific types instead of subclassing `JSONEncoder`.","message":"The `json-encoder` library uses a `singledispatch` pattern for serialization, which differs from the standard library's `json.JSONEncoder` subclassing approach. Users accustomed to `json.dumps(obj, cls=MyEncoder)` should instead register handlers using `@json_encoder.register`.","severity":"gotcha","affected_versions":"0.4.4 and earlier"},{"fix":"Evaluate the stability and feature set against your project's requirements. For new projects, consider if a more actively maintained library or a custom `JSONEncoder` solution in the standard library is more suitable, or be prepared to fork and maintain the library yourself.","message":"The project's PyPI metadata lists its 'Development Status' as '3 - Alpha' and the last release was in September 2016. While functional for its intended purpose, it may not be actively maintained or receive updates for new Python features or critical bug fixes.","severity":"deprecated","affected_versions":"0.4.4 and earlier"},{"fix":"Test thoroughly on your target Python version. For critical applications on Python > 3.5, consider alternative solutions or contribute to the project's maintenance to ensure compatibility.","message":"The PyPI classifiers explicitly list support for Python 2.7 and 3.5. While it might work on newer Python versions, explicit compatibility beyond 3.5 is not guaranteed or tested by the project maintainers due to its maintenance status.","severity":"gotcha","affected_versions":"0.4.4 and earlier"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Register a serialization function for `YourType` using the `@json_encoder.register(<YourType>)` decorator. For example:\n`from json_encoder.encoder import json_encoder`\n`@json_encoder.register(YourType)`\n`def encode_your_type(obj: YourType):`\n  `return {'value': str(obj)}`","cause":"You are trying to serialize an object whose type (`<YourType>`) does not have a registered serialization function with `json-encoder`.","error":"TypeError: Object of type <YourType> is not JSON serializable"},{"fix":"Ensure your desired JSON library (e.g., `ujson`) is installed (`pip install ujson`), then explicitly configure `json-encoder` to use it:\n`from json_encoder import use_json_library`\n`import ujson # or simplejson`\n`use_json_library(ujson)`","cause":"By default, `json-encoder` attempts to use `simplejson` if available, then falls back to the standard `json` library. Your preferred library might not be installed or explicitly configured.","error":"json.dumps is not using my preferred JSON library (e.g., ujson or simplejson)."}]}