【发布时间】:2020-02-24 11:35:58
【问题描述】:
我正在尝试找到在列表或字典中附加和存储排序的 json 数组元素的最佳方法。 我不知道哪个更好、更容易、更适合我的案例。
我已经用我想要实现的 cmets 编译了一个最小的可重现示例:
#!/usr/bin/python3.4
import json
json_data = json.loads('{'
'"data":['
'{'
'"#CLIENT":"AAA",'
'"#HOST":"host1.aaa.local",'
'"#GROUP1":"AAA-Group-1"'
'},'
'{'
'"#CLIENT":"AAA",'
'"#HOST":"host2.aaa.local",'
'"#GROUP1":"AAA-Group-1",'
'"#GROUP2":"AAA-Group-2"'
'},'
'{'
'"#CLIENT":"BBB",'
'"#HOST":"host1.bbb.local",'
'"#GROUP1":"BBB-Group-1"'
'},'
'{'
'"#CLIENT":"BBB",'
'"#HOST":"host2.bbb.local",'
'"#GROUP1":"BBB-Group-1",'
'"#GROUP2":"BBB-Group-2",'
'"#GROUP3":"BBB-Group-3"'
'},'
'{'
'"#CLIENT":"CCC",'
'"#HOST":"host1.ccc.local",'
'"#GROUP1":"CCC-Group-1",'
'"#GROUP2":"CCC-Group-2"'
'}'
']'
'}')
# List/dict to store concatenated and sorted
# json elements by number of #GROUP<i> values
grouped_list = []
print('Processing JSON elements:')
print('')
for element in json_data['data']:
print('Processing JSON element: ',element)
i = 1
print('Processing groups:')
while i < 5:
group = '#GROUP'+str(i)
if group in element:
print(group+' found in json element')
#Here: append to integer-indexed list, dict or whatever
else:
break
print('')
#for list in grouped_list:
# Do something with concatenated json elements
# 1st list should contain 'data' json array elements with only #GROUP1
# 2nd list should contain 'data' json array elements with #GROUP1 and #GROUP2 present
有一个列表/字典会很棒,我也可以像 grouped_list[2] 或其他东西一样访问它,以获取具有 #GROUP1 和 #GROUP2 存在的 json 元素,grouped_list[1] 以获取具有的 json 元素仅 #GROUP1 等。
【问题讨论】:
-
看起来你已经有了代码,你只需要将元素推送到
grouped_list -
您的访问示例毫无意义。请edit您的问题并描述示例 JSON 数据的数据结构(列表或字典)是什么样的。
-
martineau,如果没有更广泛地说明您为什么这么认为,您的评论“您的访问示例毫无意义”就毫无意义。 OP 的问题中提供的示例准确地演示了 OP 想要实现的 JSON dict/list 数据结构 - 即整数索引 JSON 元素,按 #GROUP 元素的数量分组。
标签: python arrays json list dictionary