Reputation: 1170
I'm trying to generate JSON so I can make use of the bigquery API to programmatically generate new views, but I'm having some difficulty with it. I have written a function that takes as parameters a dictionary containing a name and a datatype, and then it iterates over this loop to create the json, but I'm getting a key error when I try to do it.
def generateFieldJsonForSchema(d):
returnList = []
for name, type in d.iteritems():
print name
print type
print '{"thisName":"{0}"}'.format(name)
Here is an example dictionary
{u'Coin_Balance': 'FLOAT',
u'Item_Received_SKU': 'STRING',
u'Player_Level': 'FLOAT',
u'Player_XP': 'FLOAT',
u'Price': 'FLOAT',
u'SKU': 'STRING',
u'Ticket_Balance': 'FLOAT'}
Python (anaconda python) is generating a key error for 'thisName',but I don't understand why, because it's not an actual key, and I don't know why it thinks it's a key. Can someone give me some pointers?
Thanks
Upvotes: 1
Views: 1583
Reputation: 414605
If you need literal {}
curly brackets inside a format string; you need to escape them by doubling them {{}}
:
>>> '{"name":whatever}'.format()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '"name"'
>>> '{{"name":whatever}}'.format()
'{"name":whatever}'
To create json text, you should use json
module:
>>> import json
>>> d = dict(zip('abc', range(3)))
>>> for name in d:
... print(json.dumps({"thisName": name}))
...
{"thisName": "c"}
{"thisName": "b"}
{"thisName": "a"}
Upvotes: 4