【问题标题】:Filter JSON with null POST query return in API在 API 中过滤带有空 POST 查询返回的 JSON
【发布时间】:2020-08-03 12:39:28
【问题描述】:

我有一个 python 脚本,它连接到 graphql API 并发送一个 POST,所以返回一个 JSON,这个 API 属于一个看板,它的卡片按其工作流程排列,我的问题,我有 152 张卡片,这个查询是我返回 143,因为有些卡片没有分配给人员,只存在于工作流中。 这会为所谓的'assignees': row ['assignees'][0]['fullname'] 生成索引错误,我将try/except 与索引过滤器放在一起,并让他再次将此行添加到字典中,并给出全名Null,但这似乎失败了,因为总卡片的数量是 153 而不是 143。有没有更优雅的方法来做这个数据工程?

py:

    dataDict = {}
    for row in ModelData:

        try:

            dataDict.update(
            { row["identifier"]: 
            {'title' : row["title"], 
            'description' : row["description"], 
            'assignees' : row['assignees'][0]['fullname'], 
            'createdAt' : row["createdAt"]}})

        except IndexError as e:

            dataDict.update(
            { row["identifier"]:
            {'title' : row["title"], 
            'description' : row["description"], 
            'assignees' : "", 
            'createdAt' : row["createdAt"]}})
            pass

数据示例:

{
"identifier": "x5g",
"title": "card name",
"description": "hello world",
"assignees": {"fullname": "John"},
"createdAt": "2020-04-04"
}

产生错误的原因:

{
"identifier": "x6g",
"title": "card name 2",
"description": "hello world",
"assignees": {"fullname": ""},
"createdAt": "2020-04-04"
}

【问题讨论】:

    标签: python api graphql


    【解决方案1】:

    你可以用 if 语句来做到这一点:

    
    dataDict.update(
      { 
        row["identifier"]: {
          'title' : row["title"], 
          'description' : row["description"], 
          'assignees' : row['assignees'][0]['fullname'] if 'assignees' in row else "", 
          'createdAt' : row["createdAt"]
        }
      })
    
    I dont know what the data you get looks like without the assignees but I think you get the Idea.
    

    【讨论】:

    • 但是我删除try/except后返回索引错误 - [FAILED] Caused by: list index out of range
    • 您想查看数据模型吗?
    • 比你可能要写if len(row['assignees']) > 0 else ""
    • 在javascript中,这种方法通常如下使用row['assignees'][0]['fullname'] and row['assignees'] || " ",但是在python中我没有找到德语形式try/except
    • 所以它仍然不能在 Python 中工作?然后你能给出一些示例数据吗?
    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 2018-12-01
    • 1970-01-01
    • 2011-11-18
    • 2015-02-23
    • 2013-12-26
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多