【问题标题】:Converting a table to JSON将表转换为 JSON
【发布时间】:2020-08-17 08:48:54
【问题描述】:

我正在用 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 打印每个新行,这不是我想要的。

如何编辑它以获得我想要的输出?

【问题讨论】:

  • 实际上没有其他方法可以从 SQL 中获取它。你可以聚合这些值,但你不会得到一个真正的数组。否则,您现在必须获取结果行并将其更改为您的需要。你可以使用循环和变量来得到你想要的。
  • 使用按用户键控字典自行汇总结果,该字典本身包含字典和列表,具体取决于您希望如何按每个用户组织数据。然后,您可以使用 json 库写出 JSON 格式的字符串。

标签: python json python-3.x sqlite


【解决方案1】:

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

# define a function that takes a data array as argument
def mapData(data = []):
  # dict that is used to store aggregated rows
  results = {}
  # iterate through the data array
  for item in data:
    # aggreagate values of there is already an entry
    # in the results dict for given name
    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 will skip to next iteration
      continue 
    # create a new entry if there is no existing key
    # for given name in the results dict
    results[item["name"]] = {
      **item,
      "year": [item["year"]],
      "club": [item["club"]],
      "apps": [item["apps"]],
    }
  # return the result
  return results

# some fake data that looks like the data from sql
sqlData= [
  {
    "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",
  }
]

# pass the data into the function and assign the result
# to a new variable called aggregatedData 
aggregatedData = mapData(sqlData)

# print the result
print(aggregatedData)

# result:      
# {
#    "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"
#      ]
#    }
# }

【讨论】:

  • 您好,谢谢您的回复!我不太明白 def mapData(data) 来自哪里?我是否必须为此导入“数据”库?我是在从 SQLite 调用它之前还是之后像这样映射它?
  • 嗯,也许是时候回去看看函数定义了。 mapData 是一个带参数的函数。我称它为 data.Data 对应于您传递给函数的内容在我的情况下,我传入一个数组。所以 data 是您在最后一行看到的数组print(mapData([...])) 它是您从 SQLLte 获得的行数组。因此,您可以将您从 sqlite 获得的数组传递给函数。
  • 我把它全部拆开并添加了 cmets,以便您更容易理解它。我仍然建议复习基础知识。
猜你喜欢
  • 2017-03-19
  • 2013-09-03
  • 2021-08-27
  • 2021-02-25
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多