我正在尝试输出具有mac地址列表的JSON以及与每个mac地址关联的时间戳列表。我正在寻找的输出看起来像这样:
[
"B2:C7:23:10:A0":
[
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:14:34.305303100Z",
"2014-04-04T21:14:34.285302000Z",
"2014-04-04T21:14:33.905280300Z"
],
"C7:99:12:F2:00":
[
"2014-04-09T22:18:43.162844700Z",
"2014-04-09T22:02:39.138705700Z",
"2014-04-09T22:02:37.429608000Z",
"2014-04-09T22:02:36.966581500Z",
"2014-04-09T22:02:36.966581500Z",
"2014-04-09T22:02:36.966581500Z",
],
]
现在,我的代码使json成为上面但没有键(没有mac地址),只有时间戳组。
list_count = 0
indices = []
mac_times_array = []
for foundMacAddress in found_mac_list:
indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
grouped_times = []
for index in indices:
grouped_times.append(times[index])
mac_times_array.append(grouped_times)
stacked_array = [i for i in mac_times_array]
pprint.pprint(json.dumps(stacked_array))
所以我的问题是,如何将mac地址添加为密钥?我尝试了很多不同的东西,但没有任何工作。
答案 0 :(得分:1)
您似乎正在接受数组并将其添加到mac_times_array
。你应该使用字典,并使foundMacAddress成为关键。做这样的事情:
list_count = 0
indices = []
mac_times_dict = {}
for foundMacAddress in found_mac_list:
indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
grouped_times = []
for index in indices:
grouped_times.append(times[index])
mac_times_dict[foundMacAddress] = grouped_times
# stacked_array = [i for i in mac_times_array]
pprint.pprint(json.dumps(mac_times_dict))
(警告,代码未经测试,因为我没有输入数据)
答案 1 :(得分:0)
您期望的输出不是有效的JSON。这是:
[
{
"B2:C7:23:10:A0": [
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:14:34.305303100Z",
"2014-04-04T21:14:34.285302000Z",
"2014-04-04T21:14:33.905280300Z"
]
},
{
"C7:99:12:F2:00": [
"2014-04-09T22:18:43.162844700Z",
"2014-04-09T22:02:39.138705700Z",
"2014-04-09T22:02:37.429608000Z",
"2014-04-09T22:02:36.966581500Z",
"2014-04-09T22:02:36.966581500Z",
"2014-04-09T22:02:36.966581500Z"
]
}
]
要做到这一点,你可以这样做:
list_count = 0
indices = []
mac_times_array = []
for foundMacAddress in found_mac_list:
mac_dict = {}
indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
grouped_times = []
for index in indices:
grouped_times.append(times[index])
mac_dict[foundMacAddress] = grouped_times
mac_times_array.append(mac_dict)
pprint.pprint(json.dumps(mac_times_array))
我无法确认这一点,因为我不确定输入列表found_mac_list
和macAddressesTotal