Skip to content

Instantly share code, notes, and snippets.

@jdthorpe
Last active February 7, 2023 02:34
Show Gist options
  • Save jdthorpe/313cafc6bdaedfbc7d8c32fcef799fbf to your computer and use it in GitHub Desktop.
Save jdthorpe/313cafc6bdaedfbc7d8c32fcef799fbf to your computer and use it in GitHub Desktop.
JSON and YAML Encoders / Decoders for use with SimpleNamespaces

Load and Dump JSON and YAML to / From NamesSpaces

Why

Typed Namespaces ensure object typing is correct in the IDE!

Usage

import yaml
import json
from ns_utils import Loader, Dumper, object_hook, nsEncoder

# read from yaml
with open("./config.yaml") as fh:
    data = yaml.load(fh, Loader=Loader)

# write to yaml
print(yaml.dump(data,Dumper = Dumper))

# write to json
js_data = json.dumps(data,cls=nsEncoder)

# read from json
json.loads(js_data,object_hook=object_hook)

* Tested with Python 3.7.3

import yaml as yaml
from types import SimpleNamespace
from json import JSONEncoder
class Loader(yaml.Loader):
pass
class Dumper(yaml.Dumper):
pass
def _construct_mapping(loader, node):
loader.flatten_mapping(node)
return SimpleNamespace(**dict(loader.construct_pairs(node)))
def _ns_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.__dict__.items()
)
Dumper.add_representer(SimpleNamespace, _ns_representer)
Loader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping
)
class nsEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, SimpleNamespace):
return obj.__dict__
return super(nsEncoder, self).default(obj)
def object_hook(d):
return SimpleNamespace(**d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment