将表转换为JSON

问题描述 投票:0回答:1

我正在Python 3中构建测验应用程序。向用户显示了很多线索,他们不得不猜测这位体育明星。我当前的后端使用的是SQLite,但是我想使用Firebase建立一个实时数据库,因此需要将其更改为JSON格式。

该表当前看起来像这样:

Player Name  Difficulty     Year      Club     Apps (Goals)
player_1     easy       2014 - 2017   club        x (y)
player_1     easy       2017 - 2019   club_2      x (y)
player_2     medium     2019 -        club        x (y)

当前,用户选择难度。然后,我运行一个SQL查询,该查询为我列出了所有具有此难度的玩家。然后,该应用程序向用户显示最后三列,这是他们用来猜测玩家所需的线索。

以JSON格式输入,我认为它看起来像这样

{
    "users":
    {
        "player_1_id":
        {
            "name": "player_1",
            "difficulty": "difficulty",
            "year": [year_1, year_2, ..., year_n],
            "club": [club_in_year_1, club_in_year_2, ...., club_in_year_n],
            "apps": [apps_in_year_1, apps_in_year_2, ..., apps_in_year_n]
        },
        "player_2_id":
            "name": "player_2",
            ...
    }
}

因此每个球员姓名的年/俱乐部/应用程序列表中可以有不同数量的值。我创建并运行了以下代码:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

connection = sqlite3.connect("player_database.db")
connection.row_factory = dict_factory

cursor = connection.cursor()

cursor.execute("select * from player_history")

results = cursor.fetchall()

print(results)

connection.close()

但是这会用一个单独的ID打印每个新行,这并不是我想要的。

我将如何编辑它以获得所需的输出?

python json python-3.x sqlite
1个回答
0
投票

这里是映射数据的基本解决方案。

def mapData(data):
  results = {}
  for item in data:
    if item["name"] in results.keys():
      prev = results[item["name"]]
      prev["year"].append(item["year"])
      prev["club"].append(item["club"])
      prev["apps"].append(item["apps"])
      continue
    results[item["name"]] = {
      **item,
      "year": [item["year"]],
      "club": [item["club"]],
      "apps": [item["apps"]],
    }
  return results


print(mapData([
  {
    "name": "player_1",
    "difficulty": "difficulty",
    "year":  "2009",
    "club": "2003",
    "apps": "2005",
  },
    {
    "name": "player_1",
    "difficulty": "difficulty",
    "year":  "1999",
    "club": "1998",
    "apps": "2008",
  },
      {
    "name": "player_2",
    "difficulty": "difficulty",
    "year":  "1999",
    "club": "1998",
    "apps": "2008",
  }
]))

结果:

{
   "player_1":{
      "name":"player_1",
      "difficulty":"difficulty",
      "year":[
         "2009",
         "1999"
      ],
      "club":[
         "2003",
         "1998"
      ],
      "apps":[
         "2005",
         "2008"
      ]
   },
   "player_2":{
      "name":"player_2",
      "difficulty":"difficulty",
      "year":[
         "1999"
      ],
      "club":[
         "1998"
      ],
      "apps":[
         "2008"
      ]
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.