Json 带有记录列表的Python glom将公共的、唯一的客户机ID作为键组合在一起
我刚刚发现了glom,本教程很有意义,但我无法找到用于chrome BrowserHistory.json条目的正确规范,以创建按客户端id分组的数据结构,或者这是否是glom的正确使用。我想我可以通过在json上循环使用其他方法来实现这一点,但我希望了解更多关于glom及其功能的信息 json具有浏览器历史记录,每个历史记录条目都有一个列表,如下所示:Json 带有记录列表的Python glom将公共的、唯一的客户机ID作为键组合在一起,json,data-structures,python-3.7,nested-lists,glom,Json,Data Structures,Python 3.7,Nested Lists,Glom,我刚刚发现了glom,本教程很有意义,但我无法找到用于chrome BrowserHistory.json条目的正确规范,以创建按客户端id分组的数据结构,或者这是否是glom的正确使用。我想我可以通过在json上循环使用其他方法来实现这一点,但我希望了解更多关于glom及其功能的信息 json具有浏览器历史记录,每个历史记录条目都有一个列表,如下所示: { "Browser_History": [ { "favico
{
"Browser_History": [
{
"favicon_url": "https://www.google.com/favicon.ico",
"page_transition": "LINK",
"title": "Google Takeout",
"url": "https://takeout.google.com",
"client_id": "abcd1234",
"time_usec": 1424794867875291
},
...
我想要一个数据结构,其中所有内容都按客户机id进行分组,比如客户机id作为DICT列表的键,类似于:
{ 'client_ids' : {
'abcd1234' : [ {
"title" : "Google Takeout",
"url" : "https://takeout.google.com",
...
},
...
],
'wxyz9876' : [ {
"title" : "Google",
"url" : "https://www.google.com",
...
},
...
}
}
这是格洛姆适合的吗?我一直在玩它和阅读,但我似乎不能得到正确的规格来完成我需要的。我得到的最准确的答案是:
with open(history_json) as f:
history_list = json.load(f)['Browser_History']
spec = {
'client_ids' : ['client_id']
}
pprint(glom(data, spec))
这让我得到了所有客户机ID的列表,但我不知道如何将它们作为键组合在一起,而不是将它们作为一个大列表。任何帮助都将不胜感激,谢谢 这应该可以做到,尽管我不确定这是否是实现这一点的最“格洛姆”方法
import glom
grouping_key = "client_ids"
def group_combine (existing,incoming):
# existing is a dictionary used for accumulating the data
# incoming is each item in the list (your input)
if incoming[grouping_key] not in existing:
existing[incoming[grouping_key]] = []
if grouping_key in incoming:
existing[incoming[grouping_key]].append(incoming)
return existing
data ={ 'Browser_History': [{}] } # your data structure
fold_spec = glom.Fold(glom.T,init = dict, op = group_combine )
results = glom.glom(data["Browser_History"] ,{ grouping_key:fold_spec })