首页 > 解决方案 > Filter JSON with null POST query return in API

问题描述

I have a python script that connects to a graphql API and sends a POST, so returning me a JSON this API belongs to a kanban, where it has cards arranged by its workflow, my problem and I have 152 cards, and this query is me returning 143, because some cards are not assigned to people, only exist in the workflow. This generates an index error for the so-called 'assignees': row ['assignees'][0]['fullname'], I put try/except with index filter, and made him add this line again to the dictionary giving the full name Null, however this seems to have failed because the total number of cards is 153 and not 143. Is there a more elegant way to do this data engineering?

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

data example:

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

What generates error::

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

标签: pythonapigraphql

解决方案


您可以使用 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.

推荐阅读