gpt4 book ai didi

python - 合并 json 中的重复键

转载 作者:行者123 更新时间:2023-11-30 22:00:15 27 4
gpt4 key购买 nike

我有一个如下所示的 json:

{
"course1": [
{
"courseName": "test",
"section": "123",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course2": [
{
"courseName": "test",
"section": "456",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course2": [
{
"courseName": "test",
"section": "789",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course2": [
{
"courseName": "test",
"section": "1011",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course3": [
{
"courseName": "test",
"section": "1213",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course3": [
{
"courseName": "test",
"section": "1415",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
]
}

我想组合任何 block /对象/列表(我不知道它叫什么),它们具有相同的键值。像这样:

{
"course1": [
{
"courseName": "test",
"section": "123",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course2": [
{
"courseName": "test",
"section": "456",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
},
{
"courseName": "test",
"section": "789",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
},
{
"courseName": "test",
"section": "1011",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
],
"course3": [
{
"courseName": "test",
"section": "1213",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
},
{
"courseName": "test",
"section": "1415",
"academicHours": "3",
"day1": "1",
"room1": "0145 03 1 B 015"
}
]
}

如何在 python 中使用正则表达式来做到这一点?或任何正则表达式查询?

另外,我尝试使用 json.dumps() 并从那里开始工作,但由于某种原因,当我将它与任何包含阿拉伯字符的 json 一起使用时,它会崩溃并弄乱整个过程事物。所以不幸的是我坚持使用正则表达式。

感谢您的帮助:)

最佳答案

stdlib json 提供了一个钩子(Hook),允许使用重复键解码对象。这个简单的“扩展” Hook 应该适用于您的示例数据:

def myhook(pairs):
d = {}
for k, v in pairs:
if k not in d:
d[k] = v
else:
d[k] += v
return d

mydata = json.loads(bad_json, object_pairs_hook=myhook)

虽然the JSON specification里什么都没有为了禁止重复的键,应该首先避免:

1.1. Conventions Used in This Document

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT","SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in thisdocument are to be interpreted as described in [RFC2119].

...

  1. Objects

An object structure is represented as a pair of curly bracketssurrounding zero or more name/value pairs (or members). A name is astring. A single colon comes after each name, separating the namefrom the value. A single comma separates a value from a followingname. The names within an object SHOULD be unique.

关于python - 合并 json 中的重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54357405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com