Skip to main content

allow custom class json behavior on builtin json object

Project description

What is this?

A pip module that lets you define a __json__ method, that works like toJSON from JavaScript.
(e.g. it magically gets called whenever someone does json.dumps(your_object))

From a technical perspective, this module is a safe, backwards-compatible, reversable patch to the built-in python json object that allows classes to specify how they should be serialized.

Why?

Because sometimes someone eles's code (e.g. a pip module) tries to serialize your object, like

import json
json.dumps(list_containing_your_object)

And you'd have to fork their code to make it not throw an error.

How do I use this tool?

pip install json-fix

import json_fix # import this any time (any where) before the JSON.dumps gets called

# same file, or different file
class YOUR_CLASS:
    def __json__(self):
        # YOUR CUSTOM CODE HERE
        #    you probably just want to do:
        #        return self.__dict__
        return "a built-in object that is natually json-able"

How do I change how imported classes (numpy array, dataframe, etc) are jsonified?

There's 2 ways; the aggressive override_table or the more collaboration-friendly fallback_table. Note: some really powerful stuff can be done safely with the fallback table!

Override Table

CAUTION!

  • The override table is so powerful it even lets you change how built in objects are serialized. You can screw yourself (infinite loop) if you're using (abusing) the override table to change giant swaths of objects instead of specific classes.
  • Even if a class defines a .__json__() method, the json.override_table will take priority.
  • The order of keys matters a lot. The last entry takes the highest priority (this lets us override pip modules even if they try using the override table).

The override table is a dictionary. It has "check functions" as keys, and jsonifiers as values.

import json_fix # import this before the JSON.dumps gets called
import json
import pandas as pd

SomeClassYouDidntDefine = pd.DataFrame

# create a boolean function for identifying the class
check_func = lambda obj: isinstance(obj, SomeClassYouDidntDefine)
# then assign it to a function that does the converting
json.override_table[check_func] = lambda obj_of_that_class: json.loads(obj_of_that_class.to_json())

json.dumps([ 1, 2, SomeClassYouDidntDefine() ], indent=2) # dumps as expected

Fallback Table

If you want all python classes to be jsonable by default, we can easily do that with the fallback table. The logic is if nothing in override table, and no .__json__ method, then check the fallback table.

import json_fix # import this before the JSON.dumps gets called
import json

# a checker for custom objects
checker = lambda obj: hasattr(obj, "__dict__")
# use the __dict__ when they don't specify a __json__ method 
json.fallback_table[checker] = lambda obj_with_dict: obj_with_dict.__dict__

class SomeClass:
    def __init__(self):
        self.thing = 10

json.dumps([ 1, 2, SomeClass() ], indent=2) # dumps as expected

Like the override table, the most recently-added checker will have the highest priority.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

json_fix-1.0.2.tar.gz (4.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

json_fix-1.0.2-py3-none-any.whl (4.0 kB view details)

Uploaded Python 3

File details

Details for the file json_fix-1.0.2.tar.gz.

File metadata

  • Download URL: json_fix-1.0.2.tar.gz
  • Upload date:
  • Size: 4.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/8.7.0 pkginfo/1.12.1.2 requests/2.32.5 requests-toolbelt/1.0.0 tqdm/4.67.1 CPython/3.12.11

File hashes

Hashes for json_fix-1.0.2.tar.gz
Algorithm Hash digest
SHA256 dd775aeba78a5481127b7534cbc0fda0ae7275d812dbdac16fdcce3503f8211a
MD5 07a19773a5dd91744070eab899e9e8d5
BLAKE2b-256 1e3e84a3ef86aea3e7cbb4dca525977a6b2fd07afb1eb16c15ed77036dbe0493

See more details on using hashes here.

File details

Details for the file json_fix-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: json_fix-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 4.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/8.7.0 pkginfo/1.12.1.2 requests/2.32.5 requests-toolbelt/1.0.0 tqdm/4.67.1 CPython/3.12.11

File hashes

Hashes for json_fix-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 7a5fcc33d2a0f9966f2794ab1705be2983fcb46bdd55b57763c0ab749f757ed5
MD5 935a0269c972cf2e603f8b4e9d2bb88f
BLAKE2b-256 720f980e714185df717191531157664ce1dd06b6a3c3f042ee947ccddaa8403d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page