A better Python object for JSON

Python’s default JSON package encodes and decodes to a dict. This works well enough, but I’ve never much loved the dict type in Python. I’d rather it were an Object with attributes. dicts are verbose: data[“foo”] instead of data.foo. Also dicts throw exceptions on unknown keys, when often what I want is it just to return None. So I’m left with data.get(“foo”, None) which is awfully wordy. Basically I want something that’s as convenient and sloppy as Javascript objects.

I asked on Twitter and got some suggestions, none awesome.

Not sure if these imply overhead from copying, etc. Also they may not serialize well in the JSON module, although I imagine you can copy out a dict view on at least one of these. (More overhead!)

A yak that needs shaving. Don’t they all?

Update: see this second post

2 thoughts on “A better Python object for JSON

  1. hear hear!

    fwiw, .get() defaults to returning None, so you can use .get(‘foo’) in your example, which isn’t too much worse than [‘foo’]. i often want a {} or [] default, though.

    i pine for the common template feature that nested accesses like none.of[0].these[‘attrs’].exist happily returns None. (i did a few quick searches but couldn’t find a useful discussion of this anywhere. :/)

  2. So is the thing you’re looking for a view of a dict (provides .access, defaults to None, delegates instead of copies) that isn’t actually a dict (has too many simple property names already used)? I wonder if going back and forth (and forgetting to) between it and what the json parser returns/accepts will end up as or more annoying than typing some square brackets.

Comments are closed.