开发者社区> 问答> 正文

Python使用单个对象对JSON对象进行分组

我正在使用python格式化JSON文件并将其推入数据库。我想基于名称对值进行分组,以获取每个客户的订单信息。我无法获得正确的逻辑来提取公共值(名称)并根据公共值将其分组。谁能帮帮我吗。我是python新手,并且编写了以下逻辑。该逻辑的输出如下所示。

for row1 in cb1.n1ql_query(nql):
   col_counts += 1
   result["Category"] = row1['category']
   result["Items"] = row1['item']
   result1["Name"] = row1['name']
   result1 = result
   print(result1)

输出JSON:

[
  {
    "Items": [
      "Item1",
      "Item2",
      "Item3"
    ],
    "Category": "Food",
    "Name": "Rick"
  },
  {
    "Items": [
      "Item1",
      "Item2"
    ],
    "Category": "Drink",
    "Name": "Michael"
  },
  {
    "Items": [
      "Item1"
    ],
    "Category": "Drink",
    "Name": "Rick"
  },
  {
    "Items": [
      "Item1",
      "Item2"
    ],
    "Category": "Food",
    "Name": "Michael"
  },
  {
    "Items": [
      "Item1",
      "Item2",
      "Item3",
      "Items4"
    ],
    "Category": "Accessories",
    "Name": "Rick"
  }
]

我想要以下格式的JSON

{
"Rick":[
    {

        "Category": "Food",
        "Items": [
                    "Item1",
                    "Item2",
                    "Item3"
                ]
    },
    {
        "Category": "Drink",
        "Items": [
                    "Item1"
                ]
    },
    {
        "Category": "Accessories",
        "Items": [
                    "Item1",
                    "Item2",
                    "Item3",
                    "Items4"
                ]
    }
],
"Michael":[
    {
        "Category": "Drink",
        "Items": [
                    "Item1",
                    "Item2"
                ]
    },
    {
        "Category": "Food",
        "Items": [
                    "Item1",
                    "Item2"
                ]
    }

]}

问题来源:stackoverflow

展开
收起
is大龙 2020-03-25 09:17:35 3050 0
2 条回答
写回答
取消 提交回答
  • 代码改变世界,我们改变代码

    楼下的答案,貌似不对,但是思路是正确的。

    2020-03-30 09:38:37
    赞同 展开评论 打赏
  • 我认为您想要的是:

    resul = collections.defaultdict(lambda : collections.defaultdict(list))
    for data in js:
        resul[data['Name']][data['Category']].extend(data['Items'])
    

    它会给出:

    {
      "Rick": {
        "Food": [
          "Item1",
          "Item2",
          "Item3"
        ],
        "Drink": [
          "Item1"
        ],
        "Accessories": [
          "Item1",
          "Item2",
          "Item3",
          "Items4"
        ]
      },
      "Michael": {
        "Drink": [
          "Item1",
          "Item2"
        ],
        "Food": [
          "Item1",
          "Item2"
        ]
      }
    }
    

    回答来源:stackoverflow

    2020-03-25 09:17:44
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载