我正在使用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
我认为您想要的是:
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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。