首页 > 解决方案 > 处理来自 json 的数据以反映每个条目的单个值

问题描述

设置:

这个数据集有 50 个“问题”,在这些“问题”中,我已经捕获了我需要然后放入我的 postgresql 数据库的数据。但是当我到达“组件”时,我遇到了麻烦。我能够获得“组件”的所有“名称”的列表,但只想为每个“问题”拥有 1 个“名称”实例,其中一些有 2 个。有些是空的,想为那些。

以下是一些应该足够的示例数据:

{
 "issues": [
    {
      "key": "1",
      "fields": {
        "components": [],
        "customfield_1": null,
        "customfield_2": null
      }
    },
    {
      "key": "2",
      "fields": {
        "components": [
            {
              "name": "Testing"
            }
          ],
        "customfield_1": null,
        "customfield_2": null
      }
    },
    {
      "key": "3",
      "fields": {
         "components": [
            {
              "name": "Documentation"
            },
            {
               "name": "Manufacturing"
            }
           ],
          "customfield_1": null,
          "customfield_2": 5
      }
     }
  ]
 }

我正在寻找返回(仅用于组件名称):

['null', 'Testing', 'Documentation'] 

我设置了其他数据以进入数据库,如下所示:

values = list((item['key'],
               //components list,
               item['fields']['customfield_1'],
               item['fields']['customfield_2']) for item in data_story['issues'])

我想知道是否有一种可能的方法可以进入我在上面评论过“组件列表”的已创建组件列表中

只是为了回顾一下,我希望每个问题只有一个组件名称是否为空,并且能够将其values与其余数据一起放入变量中。组件中的第一个name也适用于每个“问题”

标签: pythonjsonpython-3.x

解决方案


假设我们正在使用一个data变量,这就是我要做的:

values = [(x['fields']['components'][0]['name'] if len(x['fields']['components']) != 0 else 'null') for x in data['issues']]

如果您有任何疑问,请告诉我。


推荐阅读