ich möchte Daten in einer JSON-Datei ablegen und diese bei Bedarf laden und an eine Funktion in meinem Script übergeben und zwar als Keyword-Argument.
Mein erster Anlauf endete so:
Code: Alles auswählen
In[7]: import json
In [8]: json.loads("""{"foo": "bar"}""")
Out[8]: {u'foo': u'bar'}
In [9]: data = json.loads("""{"foo": "bar"}""")
In [10]: def foo(**kwargs):
....: print kwargs
....:
....:
In [12]: foo(**data)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/nelson/src/Python/snippets/jinja2builder/data/<ipython console> in <module>()
TypeError: foo() keywords must be strings
Code: Alles auswählen
In [16]: foo(**{"foo": u"bar"})
{'foo': u'bar'}
Mein Ansatz war spontan dieser:
Code: Alles auswählen
def to_str_dict(arg):
"""
converts a dict with unicode-key based dict into a string-key based one.
"""
new_dict = {}
for key, value in arg.iteritems():
new_dict[str(key)] = value
return new_dict
def load(filename):
try:
with open(filename, "r") as in_file:
# die converter Funktion an den object_hook binden
data = json.load(in_file, object_hook=to_str_dict)
return data
except IOError, e:
print e
Hintergrund ist ein kleines Script, das ein jinja2-Template mit Daten aus dieser JSON Datei füttern soll - quasi als simpler Template Test.