JSON > DICT > OBJ

06.20.2014

Weird little situation came up while I was working on a research project last night. I've been taking a string representation of a dictionary and converting it into JSON to render with handlebars.js but It's finally gotten to the point that I needed a bit more from my templates.

I have jinja already in the project but problem was, jinja works really well on objects and lists/sets/tuples of objects, not so much on lists of dictionaries.

So here's what I did:
To quickly reconvert any string representation of a data structure use literal_eval from ast:

>>> import ast
>>> context = "{'a':1, 'b':2, 'foo':'bar'}"
>>> d = ast.literal_eval(context)
>>> print type(d)
<type 'dict'>


The working class

# the following class definition will take a dictionary as an argument on init
# and create an object with all keys as attributes and their corresponding values
class DictToObject:
  def __init__(self, dictionary):
    for k, v in dictionary.items():
      setattr(self, k, v)


Then to use it do this:

>>> context = "{'a':1, 'b':2, 'foo':'bar'}"
>>> d = ast.literal_eval(context)
>>> p = DictToObject(d)
>>> print(p.a)
1
>>> print(p.foo)
'bar'


The way this used to work was a python dictionary of database results was converted to a string and placed into Redis. I retrieved the string and converted it to a dictionary again only to then json.dump it back to the original AJAX call and have it passed to a handlebar template. I know, messy.

Now, after I get the string back into a dictionary, I convert it's key values into to an object, zip it up in a list and return a rendered template with the data. Presto.

Python, Jinja2, Tricks

Latest Posts

The Martian.

This book was absolutely riveting. It kept me up two nights in a row and had me imagining amber Martian landscapes around the clock. The author, Andy Weir, was previously a software engineer,...

Pragmatic MVP, References

The Pragmatic MVP is a talk I gave at TalTech Expo 2015 on building effective early stage prototypes. Below is a list of websites, articles, and books I used in preparation...

Iterables in Segments

Start with an iterable (list, tuple, set, etc.) and loop through it. Only instead of taking one element at a time, grab a segment....

Comments