0

Request

I was wondering if it's possible to take the default jsons.dump behavior and make it idempotent (return the input string) for python IPAdresses.

This would enable me to use an object while in python and use the same string in all serializations and deserializations. That way when we load the serialized JSON we don't need different control paths for the first program that loads the data and the second + N programs that load it.

Current Behavior

>>> import ipaddress
>>> import jsons
>>> import ipaddress
>>> ipaddress.IPv4Address("192.0.0.1")
IPv4Address('192.0.0.1')
>>> jsons.dump(ipaddress.IPv4Address("192.0.0.1"))
{'_ip': 3221225473}
>>> jsons.load(jsons.dump(ipaddress.IPv4Address("192.0.0.1")))
{'_ip': 3221225473}

Desired Behavior

>>> jsons.load(jsons.dump(ipaddress.IPv4Address("192.0.0.1")))
"192.0.0.1"

Desired but Probably Asking too Much

>>> jsons.load(jsons.dump(ipaddress.IPv4Address("192.0.0.1")))
IPv4Address('192.0.0.1')

Current workaround

I've changed the __repr__ method to do type conversions to string for now. But this means I have to do jsons.dump(repr(<variable>)) and this means other developers that work with my code have a potential landmine they need to be aware of.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
  • See [Making object JSON serializable with regular encoder](https://stackoverflow.com/questions/18478287/making-object-json-serializable-with-regular-encoder). – martineau Jun 23 '19 at 22:07
  • I am working with a project that is the entry point to many different AWS lambda code bases. I do not have control (aka, can't use monkey patching) as a solution for those projects. – AlexLordThorsen Jun 23 '19 at 22:09
  • In addition I am attempting to avoid custom loaders that my downstream users will need to add to their json library / `json.loads` call. That's a totally valid solution that will generate a large amount of work for people that are not me. – AlexLordThorsen Jun 23 '19 at 22:10
  • I was hoping it was possible to have class attributes that dictated loading and dumping behavior for `json.dumps` or `jsons.dumps`. – AlexLordThorsen Jun 23 '19 at 22:12
  • I don't believe that is currently possible given how the `json` module is written. To affect `jsons.dump()`, you either have to do monkey-patching or create/derive your own `json.JSONEncoder` and pass it to it as an argument. – martineau Jun 23 '19 at 22:15

0 Answers0