简体   繁体   English

尝试生成JSON时发生Python键错误

[英]Python key error when trying to generate json

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. 我正在尝试生成JSON,以便可以利用bigquery API以编程方式生成新视图,但是我遇到了一些困难。 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. 我编写了一个函数,该函数将包含名称和数据类型的字典作为参数,然后在此循环上进行迭代以创建json,但是在尝试执行此操作时遇到了关键错误。

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. Python(anaconda python)正在为“ thisName”生成键错误,但我不明白为什么,因为它不是实际的键,也不知道为什么它认为这是键。 Can someone give me some pointers? 有人可以给我一些指示吗?

Thanks 谢谢

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: 要创建json文本,您应该使用json模块:

>>> import json
>>> d = dict(zip('abc', range(3)))
>>> for name in d:
...     print(json.dumps({"thisName": name}))
... 
{"thisName": "c"}
{"thisName": "b"}
{"thisName": "a"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM