【问题标题】:Checking if a json response row exists or not in python检查python中是否存在json响应行
【发布时间】:2012-11-27 19:03:44
【问题描述】:

这是我的 json 响应

{u'kind': u'bigquery#queryResponse', u'rows': [{u'f': [{u'v': u'1'}, {u'v': u'1607 '}, {u'v': u'coriolanus'}]}, {u'f': [{u'v': u'1'}, {u'v': u'1596'}, {u 'v': u'kingjohn'}]}, {u'f': [{u'v': u'1'}, {u'v': u'1599'}, {u'v': u 'kinghenryv'}]}, {u'f': [{u'v': u'1'}, {u'v': u'1600'}, {u'v': u'merrywivesofwindsor'}] }, {u'f': [{u'v': u'1'}, {u'v': u'1602'}, {u'v': u'troilusandcressida'}]}, {u' f': [{u'v': u'1'}, {u'v': u'1592'}, {u'v': u'comedyoferrors'}]}, {u'f': [{ u'v': u'2'}, {u'v': u'1590'}, {u'v': u'3kinghenryvi'}]}, {u'f': [{u'v': u'2'}, {u'v': u'1612'}, {u'v': u'kinghenryviii'}]}, {u'f': [{u'v': u'2'} , {u'v': u'1598'}, {u'v': u'2kinghenryiv'}]}], u'jobReference': {u'projectId': u'1039435439624', u'jobId': u 'job_ffb30cfb23674f88aa5cb497e358ec05'}, u'jobComplete': True, u'totalRows': u'9', u'schema': {u'fields': [{u'type': u'INTEGER', u'name': u'sum_for_the', u'mode': u'NULLABLE'}, {u'type': u'INTEGER', u'name': u'corpus_date', u'mode': u'NULLABLE'}, {u 'type': u'STRING', u'name': u'f0_', u 'mode': u'NULLABLE'}]}}

我使用下面的 python 代码循环遍历它

resp = []
for row in listReply['rows']:
  for key,dict_list in row.iteritems():
    count = dict_list[0]
    year = dict_list[1]
    corpus = dict_list[2]
    resp.append({'count': count['v'],'year':year['v'],'corpus':corpus['v']})

如何检查此listReply['rows'] 是否存在,例如下面的 json 响应

{u'totalRows': u'0', u'kind': u'bigquery#queryResponse', u'jobComplete': True, u'jobReference': {u'projectId': u'1039435439624', u 'jobId': u'job_8efc645852c34515bcff4ab3969772fd'}, u'schema': {u'fields': [{u'type': u'INTEGER', u'name': u'sum_for_the', u'mode': u' NULLABLE'}, {u'type': u'INTEGER', u'name': u'corpus_date', u'mode': u'NULLABLE'}, {u'type': u'STRING', u'name ': u'f0_', u'mode': u'NULLABLE'}]}}

【问题讨论】:

    标签: python json parsing


    【解决方案1】:
    for row in listReply.get('rows', []):
    

    如果 listReply 有一个键“rows”,这将遍历相应的值。如果 key 不存在,则返回默认值,在这种情况下应该是一个空列表,所以 for 不会抱怨,因为它是可迭代的。

    另一种方法是在进入 for 循环之前测试密钥。

    if 'rows' in listReply:
        for row in listReply['rows']:
            ...
    

    【讨论】:

    • 但在第二种方法中,进入 for 循环之前的行是什么
    • @jade,抱歉打错了。这就是为什么我更喜欢前者 - 犯错的机会更少:)
    【解决方案2】:

    你可以使用

    if key in aDict:
      # Operations
    

    测试python字典中是否存在条目。如果它是一个空列表,您也可以这样做:

    if key in aDict and aDict[key]:
      # Operations
    

    因为评估是从左到右的,如果键缺失,第二次检查将不会执行,但如果它存在且为空,第二次检查将跳过操作。

    【讨论】:

    • 你的意思是如果行在 listReply 和 listReply['rows']
    • @jade - 是的,if 'rows' in listReply。另外,listReply.get('rows', []) 作为替代方案。
    【解决方案3】:

    要检查 dict 中是否存在密钥,请使用 in 关键字。

    >>> d = {}
    >>> 1 in d
    16: False
    >>> d[1] = 1
    >>> 1 in d
    17: True
    >>> d
    18: {1: 1}
    

    所以用你的例子

    >>> d = {u'totalRows': u'0', u'kind': u'bigquery#queryResponse', u'jobComplete': True, u'jobReference': {u'projectId': u'1039435439624', u'jobId': u'job_8efc645852c34515bcff4ab3969772fd'}, u'schema': {u'fields': [{u'type': u'INTEGER', u'name': u'sum_for_the', u'mode': u'NULLABLE'}, {u'type': u'INTEGER', u'name': u'corpus_date', u'mode': u'NULLABLE'}, {u'type': u'STRING', u'name': u'f0_', u'mode': u'NULLABLE'}]}}
    >>> 'rows' in d
    19: False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2020-03-22
      相关资源
      最近更新 更多