【问题标题】:Restructuring and reformatting json api output data重构和重新格式化 json api 输出数据
【发布时间】:2017-06-14 19:17:56
【问题描述】:

您好,我有一些 json api 输出数据,我正在尝试重组/重新格式化。以下是输出示例:

{
"playergamelogs: {
  "gamelogs": [
    {
       "game" : {
         "date" : "2016-10-13"
         "id" : "32637},
       "player": {
         "ID": "4419"},
       "team" : {
         "id" : "16}, 
       "stats" : {
          "minutes": "10"}
      },
      {
       "game": {
         "date" : "2016-10-17"
         "id" : "33737},
       "player": {
         "ID": "4419"},
       "team" : {
         "id" : "16
       }, 
       "stats" : {
          "minutes": "10"

我想做的是按玩家 ID(或名称)对数据进行分组。例如:

`{
   "playerlogs" : [
     {
      "player" : {
        "ID" : "4419"
        "team" : {
          "id" : "16"
        }, 
        "gamelogs" : [
          {
            "game" : {}
            "game" : {}
          }
         }
       "player" : {
         ....
       }
      }`

我认为实现此目的的最佳方法是使用dict.items() 和 if 语句嵌套循环以匹配适当的玩家 ID。我无法以最有效的方式进行重组。我对python相当陌生,非常感谢任何帮助。

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 不需要从一开始就选择“最有效的方式”。只需确保它正常工作并在以后关注优化即可。
  • 抱歉,不想弄乱最初的帖子。我已经添加了我在上面尝试过的内容

标签: python json api


【解决方案1】:

我建议不要将转换逻辑硬编码到 python 代码中,而是检查 MongoDB。它是一个基于 JSON 的文档数据库,您可以使用它创建此类查询。

这是一个非常简单的例子: https://docs.mongodb.com/manual/aggregation/

您的数据比较复杂,但玩家类似于示例中的 cust_id 和 game to amount。

【讨论】:

  • 感谢您的回复和信息!我正试图朝着 mongodb 的方向前进。我想最终将 api 数据存储在 mongoDB 中。我试图在添加到 mongoDB 之前清理数据。将原始输出存储在 MongoDB 中然后使用查询清理数据会更好吗?
  • 如果你还是想使用MongoDB,那为什么不使用呢?使用现有工具比重新发明它更容易。我会创建一个 MongoDB 集合并将项目存储在您的“游戏日志”列表中作为单独的文档。
【解决方案2】:

这是我如何能够解决我最初的问题并重新格式化原始数据:

for i in range(0,len(dataedit)):
playerID = dataedit[i]["player"]["ID"]
if not any(p.get('player',{}).get('ID',{}) == playerID for p in playerlog):
    playerlog.append({})
    playerlog[x]["player"] = dataedit[i]["player"]
    x+=1
gameID = dataedit[i]["game"]["id"]
playerlog[x-1]["player"]["game" + gameID] = dataedit[i]["game"]
playerlog[x-1]["player"]["game" + gameID]["stats"] = dataedit[i]["stats"]
playerlog[x-1]["player"]["game" + gameID]["team"] = dataedit[i]["team"]

由于我仍在学习,我很想获得有关如何改进的反馈/cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多